我需要以特定方式合并两个列表,如下所述。这个实现使用递归和工作但似乎kludgy。有没有人知道用LINQ做更好的方法,似乎应该有类似SelectMany
的东西可以引用回外部(unflattened)元素,但我找不到任何东西
/// <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;
}
答案 0 :(得分: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();
}
}
}
可以很容易地修改此函数以将布尔值传递给结果选择器函数,以表示是否存在第一个或第二个元素,如果您需要明确检查(而不是使用{{1 lambda中的}或default(TFirst)
。
答案 1 :(得分: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));
}
答案 2 :(得分: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]));
}