Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '||' cannot be applied to operands of type 'lambda expression' and 'lambda expression'

Tags:

c#

linq

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?

See also

  • LINQ where or filter c#
like image 691
Ian Boyd Avatar asked Jan 17 '12 19:01

Ian Boyd


2 Answers

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)
);
like image 185
Thomas Levesque Avatar answered Sep 21 '22 23:09

Thomas Levesque


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
);
like image 29
Justin Niessner Avatar answered Sep 18 '22 23:09

Justin Niessner