Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'm trying to get All AnotherList items of a specific type using Lambda

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

But I get the

Can not implicitly convert type IEnumerable to Generic.List

error

Any idea how to solve this?

Many thanks.

like image 835
Maya Avatar asked Feb 26 '23 01:02

Maya


1 Answers

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

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

Edit based on comments

If what you want is the SomeObjects that have a list containing an item that matches the category you can do that using.

someobjectsfiltered = someobjects.Where( s => s.AnotherList.Any( a => a.category == SomeCategory ))
                                 .ToList();
like image 71
tvanfosson Avatar answered Mar 08 '23 02:03

tvanfosson