开发者

how to filter from nested collections without ForEach?

I have an entity say Type A with property type List of B. Type B also has a property of type List of C.

I want to apply the filter on object of A such that there would be only C objects in the List of C for which their Selected property is True.

This can be done like:

A objA = A.ListB.ForEach(b => {b.ListC.RemoveAll(c => c.Selected == false);});

But I don't have to remove all those C Objects which have Selected = false. I only want to filter them.

Any ideas?


More explanation: There is an object of Type A, with List of B property. In each B object of A's List of B, there exists a List of C property. C object has a Selected Property. Now, all I need is- an object of A with List of B, where in each of B's List of C has only those C objects which have Selected = true. The desirable output is type A. List B shouldn't be filtered only Lis开发者_JAVA百科t C needs to be filtered.


What about this:

A.ListB.Where( b => b.ListC.Exists( c => c.Selected ) )

Is this what you want?


If you want a list containing all the selected C objects, you can do this:

List<C> selectedC = A.ListB.SelectMany( b => b.ListC.Where( c => c.Selected)).ToList();


var qry = from b in A.ListB
          select new {B=b,ListC=b.ListC.Where(x => x.Selected).ToList()};

note that this is just an anonymous tuple; we can't show code to reconstruct an A/B etc without more info on how your code is structured, what props there are, etc

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜