Use LINQ where list of items contains any component in a list of components

前端 未结 2 756
盖世英雄少女心
盖世英雄少女心 2021-01-26 10:18

Using LINQ, how can I find a list of items where it\'s list of components contains a component from another list of components?

Structure:

class Item
{
          


        
相关标签:
2条回答
  • 2021-01-26 10:55

    It should be the other way around: first the Any and then the Contains. You would like to get all items that have any of there components contained in the components list.

    Also don't use the Select if you'd like to get a list of Item back:

    var result = items.Where(i => i.Components.Any(c => components.Contains(c.Name)));
    
    0 讨论(0)
  • 2021-01-26 10:55

    It because Any expects boolean value, but you return string: x.Name.ToString.

    You can check intersection of two sequences in you case:

    items.Where(x => x.Components.Intersect(components).Any())
    

    Intersect will return non-empty sequence, if both item.Components and components contain same elements. Then Any without parameters will return true, if the sequence is non-empty.

    0 讨论(0)
提交回复
热议问题