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
{
public List<Component> Components {get;set;}
}
class Component
{
public string Name {get;set;}
}
Example:
var components = new List<string> { "C1", "C2" , "C3" }
var items = new List<Item>
{
new Item("IT1")
{
Components = new List<Component> { "C1", "C4","C5" }
},
new Item("IT2")
{
Components = new List<Component> { "C6", "C7","C8" }
},
new Item("IT3")
{
Components = new List<Component> { "C2", "C0","C9" }
}
}
The output will returns items IT1 and IT3.
I tried the following:
items
.Select(i => i.Components)
.Where(c => components.Contains(c.Any(x => x.Name.ToString()));
I am getting the following error:
Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
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)));
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.