Union multiple number of lists in C#

后端 未结 2 528
猫巷女王i
猫巷女王i 2020-12-18 21:18

I am looking for a elegant solution for the following situation:

I have a class that contains a List like

class MyClass{ 
...
 public List

        
2条回答
  •  一向
    一向 (楼主)
    2020-12-18 21:45

    You are looking for SelectMany() + Distinct() :

    List 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 instead, you do not have to convert to a list at all.

提交回复
热议问题