I am looking for a elegant solution for the following situation:
I have a class that contains a List like
class MyClass{
...
public List
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.
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.