In my example i want to get promotion elements for a promo code name that is provided if name is not provided then take all available promotions.
var result = from row in promoCodes.AsEnumerable()
where (
!String.IsNullOrEmpty(fieldTitle) &&
!String.IsNullOrEmpty(filterValue) &&
row[fieldTitle].Equals(filterValue)
) || true
select new PromoCodeInfoContainer
{
BannerLink = row["BannerLink"] as string
....
};
I tried to follow SQL technique where if no conditions provided then OR will be whatever that doesn’t impact selection (|| true). In linq this didn’t work, it always returns all entries regardless of “fieldTitle” and “filterValue” are not empty. Can anybody suggest a right way to do it?
Firstly, remove the
|| true– that will return every row, always – hence the problem.One nice way to do this would be composition – this then avoids the need to test the
fieldTitle/fieldValuefor every row when they have values, or do anything much at all per-row if they are blank:Note I also reversed the
Equalsso that the thing-we-know-isn’t-null is on the left; although depending on the data-types,Equals(x,y)orx == ymay be preferable.