Maya
Maya

Reputation: 1412

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.

Upvotes: 4

Views: 2256

Answers (3)

Samara
Samara

Reputation: 387

@tvanfosson @Maya Not sure how "Any" would work here since it will come back with true all the time causing the whole AnotherList (the inner list) to be selected back, if that "Category" type exist once in the inner list then all of its contents will be selected including those with the unwanted Category types.

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532595

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();

Upvotes: 5

Adam Rackis
Adam Rackis

Reputation: 83366

SelectMany returns IEnumerable<T> - you can convert that to a List<T> by simply adding a call to ToList() onto the end.

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

Upvotes: 1

Related Questions