What is the simplest way to achieve O(n) performance when creating the union of 3 IEnumerables?

前端 未结 3 1519
心在旅途
心在旅途 2021-02-07 00:51

Say a, b, c are all List and I want to create an unsorted union of them. Although performance isn\'t super-critical, they might have 10,000 entries in each

3条回答
  •  面向向阳花
    2021-02-07 01:22

    While @Tim Schmelter is right about linear time complexity of the Enumerable.Union method, chaining multiple Union operators has the hidden overhead that every Union operator internally creates a hash set which basically duplicates the one from the previous operator (plus additional items), thus using much more memory compared to single HashSet approach.

    If we take into account the fact that Union is simply a shortcut for Concat + Distinct, the scalable LINQ solution with the same time/space complexity of the HashSet will be:

    a.Concat(b).Concat(c)...Concat(x).Distinct()
    

提交回复
热议问题