gpt4 book ai didi

c# - 使用组合器 lamba 合并 C# 中的 2 个列表

转载 作者:行者123 更新时间:2023-11-30 14:33:16 28 4
gpt4 key购买 nike

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

/// <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;
}

最佳答案

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)default(TSecond) 在 lambda 中)。

关于c# - 使用组合器 lamba 合并 C# 中的 2 个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805377/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com