Lambda for nested arrays

I have a list of custom objects:

List<SomeObject> someobjects = getAllSomeObjects();
List<SomeObject> someobjectsfiltered = new List<SomeObject>();

class SomeObject
{
  List <AnotherList>
}

class AnotherList
{
  public string Name{get;set;}
  public Categories category {get;set;}
}

So, I am trying to get all AnotherList elements of a specific type using Lambda

someobjectsfiltered = someobjects.SelectMany(s => s.AnotherList.FindAll(a => a.category == SomeCategory));

But I get

Cannot implicitly convert type to IEnumerable to Generic.List

Error

Any idea how to solve this?

Many thanks.

+3
source share
3 answers

You need to throw ToList()in the end or change the type of the result to IEnumerable<SomeObject>, because, as the error says, you cannot assign IEnumerable<T>a type to a variable List<T>.

someobjectsfiltered = someobjects.SelectMany(s => s.AnotherList.FindAll(a => a.category == SomeCategory))
                                 .ToList();

Edit based on comments

If you want, this SomeObjectsone that has a list containing an item that matches the category that you can do with.

someobjectsfiltered = someobjects.Where( s => s.AnotherList.Any( a => a.category == SomeCategory ))
                                 .ToList();
+5
source

@tvanfosson @Maya , "Any" , , AnotherList ( ) , "" , , .

+2

SelectManyreturns IEnumerable<T>- you can convert it to List<T>by simply adding a call to ToList()at the end.

someobjectsfiltered = someobjects.SelectMany(s => s.AnotherList.FindAll(a => a.category == SomeCategory)).ToList();
+1
source

Source: https://habr.com/ru/post/1793266/


All Articles