追加/串联两个IEnumerable序列
我有两组数据行。它们每个都是IEnumerable。我想将这两个列表附加/连接到一个列表中。我确定这是可行的。我不想进行for循环,并注意到两个列表上都有Union方法和Join方法。有想法吗?
I have two sets of datarows. They are each IEnumerable. I want to append/concatenate these two lists into one list. I'm sure this is doable. I don't want to do a for loop and noticed that there is a Union method and a Join method on the two Lists. Any ideas?
假设您的对象属于同一类型,则可以使用 Union
或 Concat
。请注意,与SQL UNION
关键字一样, Union
操作将确保消除重复项,而 Concat
(例如 UNION ALL
)只会将第二个列表添加到第一个列表的末尾。
Assuming your objects are of the same type, you can use either Union
or Concat
. Note that, like the SQL UNION
keyword, the Union
operation will ensure that duplicates are eliminated, whereas Concat
(like UNION ALL
) will simply add the second list to the end of the first.
IEnumerable<T> first = ...;
IEnumerable<T> second = ...;
IEnumerable<T> combined = first.Concat(second);
或
IEnumerable<T> combined = first.Union(second);
如果它们是不同类型,则必须 Select
变成普通的东西。例如:
If they are of different types, then you'll have to Select
them into something common. For example:
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
的实例。
Where ConvertToT(TOne f)
and ConvertToT(TTwo s)
represent an operation that somehow converts an instance of TOne
(and TTwo
, respectively) into an instance of T
.