合并2个集合

时间:2012-03-22 02:51:43

标签: c#

如何组合2个集合,使得结果集合包含来自两个集合的值

示例: - Col A = [1,2,3,4] Col B = [5,6,7,8]

结果Col C = [1,5,2,6,3,7,4,8]

5 个答案:

答案 0 :(得分:2)

int[] a = { 1, 2, 3, 4 };
int[] b = { 5, 6, 7, 8 };
int[] result = a.SelectMany((n, index) => new[] { n, b[index] }).ToArray();

如果集合a和b的长度不同,则需要谨慎使用b[index],可能需要:index >= b.Length ? 0 : b[index]

答案 1 :(得分:2)

如果集合的长度不一定相同,请考虑扩展方法:

public static IEnumerable<T> AlternateMerge<T>(this IEnumerable<T> source, 
                                               IEnumerable<T> other)
{
    using(var sourceEnumerator = source.GetEnumerator())
    using(var otherEnumerator = other.GetEnumerator())
    {
        bool haveItemsSource = true;
        bool haveItemsOther = true;
        while (haveItemsSource || haveItemsOther)
        {
            haveItemsSource = sourceEnumerator.MoveNext();
            haveItemsOther = otherEnumerator.MoveNext();

            if (haveItemsSource)
                yield return sourceEnumerator.Current;

            if (haveItemsOther)
                yield return otherEnumerator.Current;
        }
    }
}

并使用:

List<int> A = new List<int> { 1, 2, 3 };
List<int> B = new List<int> { 5, 6, 7, 8 };

var mergedList = A.AlternateMerge(B).ToList();

答案 2 :(得分:2)

根据输入的类型和所需的输出类型,有很多方法可以做到这一点。然而,我没有知道库方法;你必须“自己动手”。

一种可能性是linq样式的迭代器方法,假设我们对输入集合的所有了解都是它们实现IEnumerable<T>

static IEnumerable<T> Interleave(this IEnumerable<T> a, IEnumerable<T> b)
{
    bool bEmpty = false;
    using (var enumeratorB b.GetEnumerator())
    {
        foreach (var elementA in a)
        {
            yield return elementA;
            if (!bEmpty && bEnumerator.MoveNext())
                yield return bEnumerator.Current;
            else
                bEmpty = true;
        }
        if (!bEmpty)
            while (bEnumerator.MoveNext())
                yield return bEnumerator.Current;
    }
}

答案 3 :(得分:1)

假设两个集合的长度相等:

Debug.Assert(a.Count == b.Count);

for (int i = 0; i < a.Count; i++)
{
   c.Add(a[i]);
   c.Add(b[i]);
}

Debug.Assert(c.Count == (a.Count + b.Count));

答案 4 :(得分:-2)

使用Linq的Union扩展名,例如:

var colA = new List<int> { 1, 2, 3, 4 };
var colB = new List<int> { 1, 5, 2, 6, 3, 7, 4, 8};

var result = colA.Union( colB); // 1, 2, 3, 4, 5, 6, 7, 8