score:35

Accepted answer

you are looking for selectmany() + distinct() :

list<someotherclass> ret =  myclasslist.selectmany( x => x.someotherclasses)
                                       .distinct()
                                       .tolist();

selectmany() will flatten the "list of lists" into one list, then you can just pick out the distinct entries in this enumeration instead of using union between individual sub-lists.

in general you will want to avoid side effects with linq, your original approach is kind of abusing this my modifying ret which is not part of the query.

tolist() is required since each standard query operator returns a new enumeration and does not modify the existing enumeration, hence you have to convert the final enumeration result back to a list. the cost of tolist() is a full iteration of the enumeration which, in most cases, is negligible. of course if your class could use an ienumerable<someotherclass> instead, you do not have to convert to a list at all.

score:0

you should have a look at selectmany. something like this should generate your "flat" list:

myclasslist.selectmany(b => b.someotherclasses)

it will return a ienumerable<someotherclass> which you can filter/process further.


Related Query

More Query from same tag