Tuesday, January 11, 2011

Using if/else in your LINQ query

Sometimes you're faced with needing an if/else in your LINQ query. This is pretty straight forward with LINQ using a ternary operator. Say for instance we have a database table called CoolObjects, with the following structure:

ID
ParentID
Name


This table can reference itself with ParentID => ID. Now, let's say you have a method that can look up this object by the id, and it takes a boolean as to whether or not to return the children as well:

public IEnumerable GetMyCoolObjects(int id, bool returnChildren)...

Using a ternary operator we can write a LINQ statement like this:

var items = from x in CoolObjects
where (returnChildren ? u.ID == id || u.ParentID == id : u.ID == id)
select new CoolObject
{
Name = u.Name,
};
return items;


Pretty simple! Enjoy!

No comments:

Post a Comment