Plexis Plexis
Plexis Plexis

Reputation: 302

Searching a List of List

I have the following object:

List<List<MyObj>> lst;

I need to find a list of all the objects (List< MyObj >) in the inner list, that has ID equal 1.

I tried:

lst.Where(x => x.FindAll(y=> y.ID== "1"));

lst.FindAll(x => x.FindAll(y=> y.ID== "1"));

and also tried to use Any() but no luck.

Upvotes: 2

Views: 191

Answers (4)

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11482

Let me add another option to the already good set of options. It is using Hashset<T> for search, by converting the internal List<T>, this would help when data size is more, since Hashset<T> has O(1) search instead of O(N) for List<T>

List<List<MyObj>> lst;

var result = lst.where(x => 
             {
               // Assuming ID to be string type
               var hashset = new Hashset<string>(x.Select(y => y.ID));
               return hashset.Contains("1");
              }
           );

In case you are not keen to do conversion, then following code would do:

var result = lst.where(x => x.Any(y => y.ID == "1"));

result will be of type List<List<MyObj>>, which will be filtered, currently we are are supplying Func<T,bool> to the Enumerable.Where, when data is supplied at run-time, then its easier to construct Expression<Func<T,bool>>, which gets compiled at run-time into correct Func<T,bool> delegate to filter actual list

Upvotes: 1

Konamiman
Konamiman

Reputation: 50273

SelectMany is your friend. Example:

var listOfListsOfStrings = new List<List<string>>();

listOfListsOfStrings.Add(new List<string>() {"a", "b"});
listOfListsOfStrings.Add(new List<string>() {"c", "d"});

var allStrings = listOfListsOfStrings.SelectMany(s => s);

Console.WriteLine(string.Join(", ", allStrings.ToArray())); //prints: a, b, c, d

So in your case you just need:

lst.SelectMany(x => x).Where(y => y.ID == "1")

Upvotes: 2

Igor
Igor

Reputation: 62213

List<MyObj> list1 = lst.SelectMany(x => x.Where(y=> y.ID== "1")).ToList();

or

List<List<MyObj>> list2 = lst.Where(x => x.Any(y=> y.ID== "1")).ToList();

depending on what it is you want as a result..

Upvotes: 4

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

You can use SelectMany() to flatten the lists and then filter the elements:

var result = lst.SelectMany(x => x).Where(y => y.ID == "1").ToList();

Upvotes: 6

Related Questions