本文介绍了追加/串联两个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.

这篇关于追加/串联两个IEnumerable序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:04