Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...