Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query list contains a list

Tags:

c#

linq

I have 2 a class's:

public class ObjectA
{
    public int Id;
    public string Name;
}

public class ObjectB
{
    public int Id;
    public string Name;
    public List<ObjectA> ListOfObjectA;
}

So I have two lists: One of ObjectB (ListObjectB) and Another contains a list of id's of ObjectA (called ListOfIdsA). If this i want to get a list of ObjectB where ObjectB.ListOfObjectA is in the ListOfIdsA.

My first (and wrong) approach was

ListObjectB.Where(p=> ListOfIdsA.Contains(p.ListOfObjectA.Select(b=>b.Id)))

But this obviously throws an exception. I google it, stackoverflowed, but I'm thinking that my search skills aren't going so well in this, can anybody give a ninja awser of this? (Prefereably in lambda expression)

like image 513
Berto Avatar asked Mar 02 '10 15:03

Berto


People also ask

How use contains in LINQ query?

To check for an element in a string, use the Contains() method. The following is our string array. string[] arr = { "Java", "C++", "Python"}; Now, use Contains() method to find a specific string in the string array.

How to check Contains in LINQ C#?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

Where Contains in LINQ?

LINQ Contains is quantifier operator. In LINQ Contains it also checks with the data sources, to check whether the collection of lists contains their desired element or not, and then it returns the result as either true or false based on the expected outcomes of the result.


1 Answers

Are you trying to get a list of ObjectBs where all of the ObjectAs are in ListOfIdsA, or any of them?

I think you want either:

ListObjectB.Where(p => p.ListOfObjectA.Any(x => ListOfIdsA.Contains(x.Id)))

or

ListObjectB.Where(p => p.ListOfObjectA.All(x => ListOfIdsA.Contains(x.Id)))

(You may well want to make ListOfIdsA a HashSet<string> if it's of significant size, btw.)

like image 155
Jon Skeet Avatar answered Sep 26 '22 17:09

Jon Skeet