How do i construct a LINQ WHERE
clause that contains OR
?
i have a list of objects, and i want to return those that match a search criteria.
The contained objects have many properties, and as long as any match the criteria, i want to return it:
IEnumerable<Item> list;
String keyword;
...
var results = list.Where(
(item => item.Name.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
||
(item => item.Description.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
||
(item => item.Description.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
||
(item => item.ItemType.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
||
(item => item.ItemID.ToString().StartsWith(keyword, StringComparison.CurrentCultureIgnoreCase))
||
(items => items.Value.ToString().StartsWith(keyword, StringComparison.CurrentCultureIgnoreCase))
);
But that fails to compile:
Operator '||' cannot be applied to operands of type 'lambda expression' and 'lambda expression'
How do i construct a LINQ WHERE
clause that contains OR
?
Just do all your tests in the same lambda expression...
IEnumerable<Item> list;
String keyword;
...
var results = list.Where(
item => item.Name.Contains(keyword, StringComparison.CurrentCultureIgnoreCase)
|| item.Description.Contains(keyword, StringComparison.CurrentCultureIgnoreCase)
|| item.Description.Contains(keyword, StringComparison.CurrentCultureIgnoreCase)
|| item.ItemType.Contains(keyword, StringComparison.CurrentCultureIgnoreCase)
|| item.ItemID.ToString().StartsWith(keyword, StringComparison.CurrentCultureIgnoreCase)
|| items.Value.ToString().StartsWith(keyword, StringComparison.CurrentCultureIgnoreCase)
);
You're trying to express each condition inside of a separate lambda expression which is incorrect.
You want to have all of your expressions inside of a single lambda expression:
var results = list.Where(item =>
(item.Name.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
|| (item.Description.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
|| (item.Description.Contains(keyword, StringComparison.CurrentCultureIgnoreCase))
// and so on
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With