c# - Enumerable.Concat 是否总是附加在第一个集合的末尾?

标签 c# ienumerable concat

Enumerable.Concat 是否总是追加到第一个集合的末尾?

例子:

object someObject = new object();
List<object> listA = new List<object>();
listA.Add(new int());
object item = listA.Concat(new object[] { (object)new float() }).FirstOrDefault();

每次使用 Concat 后,是否保证 itemint 而不是 float?这意味着:

[0] int
[1] float

MSDN 没有说明结果集合中的元素顺序,但是示例显示顺序是第一个集合中的元素然后是第二个集合中的元素。

最佳答案

Concat 是一种 LINQ 方法。这意味着它是一个查询。它不会创建列表或其他类型的集合,而是创建序列。

Concat 实际上所做的是合并 两个源序列。当您遍历 Concat 的结果时,您首先遍历第一个序列,然后遍历第二个序列。因此,顺序永远不会改变。

所以,是的

the item will be int not float after Concat on every use


The MSDN says nothing about element order

嗯呢does say

Concatenates two sequences.

concatenate 意味着将一个放在另一个之后,而不是将它们混在一起。


来自reference source :

public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    return ConcatIterator<TSource>(first, second);
}

static IEnumerable<TSource> ConcatIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second) {
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element;
}

所以你看到两个连续的 foreach 将首先产生第一个序列的元素,然后是第二个序列的元素。

关于c# - Enumerable.Concat 是否总是附加在第一个集合的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221928/

相关文章:

string - TCL 字符串连接

python - 基于公共(public)列合并多个数据框

PHP MySQL 将用户表加入多列和多行

c# - 在 Windows 窗体中使用 OpenFileDialog 读取文本文件

c# - 如何获取另一个线程的 ThreadStatic 值?

c# - ASP.NET MVC POST 中的模型绑定(bind) IEnumerable?

c# - ForEach 超过对象错误

c# - 如何为多个foreach实现正确的IEnumerator接口(interface)?

c# - HttpPostedFileBase 与 HttpPostedFileWrapper 的关系

c# - 不使用 lambda 表达式时的 LINQ 多重排序依据