我有两组数据行。它们都是 IEnumerable。我想将这两个列表附加/连接到一个列表中。我确定这是可行的。我不想做一个 for 循环并注意到两个列表上有一个 Union 方法和一个 Join 方法。有什么想法吗?
最佳答案
假设您的对象属于同一类型,您可以使用 Union
或 Concat
。请注意,与 SQL UNION
关键字一样,Union
操作将确保消除重复项,而 Concat
(如 UNION ALL
) 将简单地将第二个列表添加到第一个列表的末尾。
IEnumerable<T> first = ...;
IEnumerable<T> second = ...;
IEnumerable<T> combined = first.Concat(second);
或
IEnumerable<T> combined = first.Union(second);
如果它们属于不同的类型,那么您必须选择
它们成为共同的东西。例如:
IEnumerable<TOne> first = ...;
IEnumerable<TTwo> second = ...;
IEnumerable<T> combined = first.Select(f => ConvertToT(f)).Concat(
second.Select(s => ConvertToT(s)));
其中 ConvertToT(TOne f)
和 ConvertToT(TTwo s)
表示以某种方式转换 TOne
实例的操作(和 TTwo
,分别)转换为 T
的实例。
关于c# - 附加/连接两个 IEnumerable 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4961910/