3

我需要以特定方式合并两个列表,如下面的函数所述。这个实现使用递归并且可以工作,但看起来很笨拙。有谁知道使用 LINQ 执行此操作的更好方法,似乎应该有类似 aSelectMany可以引用外部(未展平)元素但我找不到任何东西

/// <summary>
/// Function merges two list by combining members in order with combiningFunction
/// For example   (1,1,1,1,1,1,1) with 
///               (2,2,2,2)       and a function that simply adds
/// will produce  (3,3,3,3,1,1,1)
/// </summary>
public static IEnumerable<T> MergeList<T>(this IEnumerable<T> first, 
                                          IEnumerable<T> second, 
                                          Func<T, T, T> combiningFunction)
{
    if (!first.Any())
        return second;

    if (!second.Any())
        return first;

    var result = new List<T> {combiningFunction(first.First(), second.First())};
    result.AddRange(MergeList<T>(first.Skip(1), second.Skip(1), combiningFunction));

    return result;
}
4

3 回答 3

5

Enumerable.Zip正是你想要的。

var resultList = Enumerable.Zip(first, second,
// or, used as an extension method:  first.Zip(second,
    (f, s) => new
              {
                  FirstItem = f,
                  SecondItem = s,
                  Sum = f + s
              });

编辑:似乎我没有考虑到即使一个列表完成也会继续的“外部”压缩风格。这是一个解决方案:

public static IEnumerable<TResult> OuterZip<TFirst, TSecond, TResult>(
    this IEnumerable<TFirst> first, IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    using (IEnumerator<TFirst> firstEnumerator = first.GetEnumerator())
    using (IEnumerator<TSecond> secondEnumerator = second.GetEnumerator())
    {
        bool firstHasCurrent = firstEnumerator.MoveNext();
        bool secondHasCurrent = secondEnumerator.MoveNext();

        while (firstHasCurrent || secondHasCurrent)
        {
            TFirst firstValue = firstHasCurrent
                ? firstEnumerator.Current
                : default(TFirst);

            TSecond secondValue = secondHasCurrent
                ? secondEnumerator.Current
                : default(TSecond);

            yield return resultSelector(firstValue, secondValue);

            firstHasCurrent = firstEnumerator.MoveNext();
            secondHasCurrent = secondEnumerator.MoveNext();
        }
    }
}

default(TFirst)如果您需要显式检查(而不是使用 lambda或default(TSecond)在 lambda 中),则可以轻松修改此函数以将布尔值传递给结果选择器函数,以表示是否存在第一个或第二个元素。

于 2013-05-29T04:36:38.633 回答
1

像这样的东西怎么样

public static IEnumerable<T> MyMergeList<T>(this IEnumerable<T> first,
                                  IEnumerable<T> second,
                                  Func<T, T, T> combiningFunction)
{
    return Enumerable.Range(0, Math.Max(first.Count(), second.Count())).
        Select(x => new
                        {
                            v1 = first.Count() > x ? first.ToList()[x] : default(T),
                            v2 = second.Count() > x ? second.ToList()[x] : default(T),
                        }).Select(x => combiningFunction(x.v1, x.v2));
}
于 2013-05-29T04:53:18.410 回答
0

只是一个好的老式循环有什么问题。当然,它没有那么花哨,但它非常简单,您不必使用递归。

var firstList = first.ToList();
var secondList = second.ToList();
var firstCount = first.Count();
var secondCount = second.Count();
var result = new List<T>();
for (int i = 0; i < firstCount || i < secondCount; i++)
{
    if (i >= firstCount)
        result.Add(secondList[i]);
    if (i >= secondCount)
        result.Add(firstList[i]);

    result.Add(combiningFunction(firstList[i], secondList[i]));
}
于 2013-05-29T04:32:15.437 回答