开发者

Lambda for nested arrays

开发者 https://www.devze.com 2023-02-11 06:04 出处:网络
I have a List of custom objects: List<SomeObject> someobjects = getAllSomeObjects(); List<SomeObject> someobjectsfiltered = new List<SomeObject>();

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 tha开发者_如何学JAVAnks.


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


@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.


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

精彩评论

暂无评论...
验证码 换一张
取 消