LINQ中的空序列

9 c# linq

我最近遇到了一个与LINQ有关的面试问题.

空序列有什么用??他问"我是否想要你使用那个,你在哪里适合它?"

     public static IEnumerable<TResult> Empty<TResult>()
     {
        yield break;
     }
Run Code Online (Sandbox Code Playgroud)

我没有回答.感谢帮助.

Sta*_* R. 3

当您想要快速创建一个IEnumerable<T>新的引用时,您可以使用它,而不必创建对新的引用List<T>并利用yield关键字。

List<string[]> namesList =
    new List<string[]> { names1, names2, names3 };

// Only include arrays that have four or more elements
IEnumerable<string> allNames =
    namesList.Aggregate(Enumerable.Empty<string>(),
    (current, next) => next.Length > 3 ? current.Union(next) : current);
Run Code Online (Sandbox Code Playgroud)

请注意Union的使用,因为它不是List ,因此您无法调用Add方法,但您可以IEnumerable

  • 使用 LINQ 加入一堆列表的最快方法是 namesList.SelectMany(list =&gt; list.Length&gt;4 ? list : Enumerable.Empty&lt;string&gt;()).Distinct()。使用聚合和联合来做这件事效率极低。聚合和连接更好,但仍然是 O(Nsquared) 和 O(N) 空间。SelectMany/Distinct 的空间复杂度为 O(N) 和 O(1)(仅创建 3 个对象)。 (2认同)