Martin Martin - 15 days ago 10
C# Question

Elegant Boolean LINQ Query flexible for Active = true or Active = true or false

I've got a LINQ query to return lookup data. A bool parameter is passed in called active.

I want to either return only the rows where active = true
OR
return all rows regardless of active status
Is there an elegant way to do this in the where clause of LINQ?

return await (from p in db.PackSizeTypes.AsNoTracking()
where p.Active == true
orderby p.ID

select new PackSizeTypeObject
{
ID = p.ID,
Name = p.Name.Trim(),
LastEditedDate = p.LastEditedDate,
LastEditedBy = p.LastEditedBy,
Active = p.Active
}).ToListAsync();


Is there a way to use a ternary operator in the where clause to provide this switch?

Answer
 IEnumerable<PackSizeTypeObject> MyPackSizeTypeObjects(bool? isActive)
{

return await (from p in db.PackSizeTypes.AsNoTracking()
          where  p.Active == (isActive == null ? p.Active : isActive)
          orderby p.ID

 select new PackSizeTypeObject
      {
          ID = p.ID,
          Name = p.Name.Trim(),
          LastEditedDate = p.LastEditedDate,
          LastEditedBy = p.LastEditedBy,
          Active = p.Active
      }).ToListAsync();
}