本文介绍了有没有一种简单的方法使用LINQ to合并两个有序序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于
IEnumerable<T> first;
IEnumerable<T> second;
和两个第一
和第二
由比较器排序 Func键&LT; T, T,INT&GT;
,对于平等返回0,-1时,第一条就是小和1时,第二个是小
and that both first
and second
are ordered by a comparer Func<T, T, int>
that returns 0 for equality, -1 when the first is "smaller" and 1 when the second is "smaller".
有没有使用LINQ to的方式,使所产生的序列也由同一个比较器下令两个序列合并一个直接的方式?
我们目前正在使用的是手工制作的算法,工作,但一个直接的LINQ语句的可读性是preferable。
We're currently using a hand-crafted algorithm that works, but the readability of a straight-forward LINQ statement would be preferable.
推荐答案
您可以定义此扩展方法。类似
You could define an extension method for this. Something like
public static IEnumerable<T> MergeSorted<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, int> comparer)
{
using (var firstEnumerator = first.GetEnumerator())
using (var secondEnumerator = second.GetEnumerator())
{
var elementsLeftInFirst = firstEnumerator.MoveNext();
var elementsLeftInSecond = secondEnumerator.MoveNext();
while (elementsLeftInFirst || elementsLeftInSecond)
{
if (!elementsLeftInFirst)
{
do
{
yield return secondEnumerator.Current;
} while (secondEnumerator.MoveNext());
yield break;
}
if (!elementsLeftInSecond)
{
do
{
yield return firstEnumerator.Current;
} while (firstEnumerator.MoveNext());
yield break;
}
if (comparer(firstEnumerator.Current, secondEnumerator.Current) < 0)
{
yield return firstEnumerator.Current;
elementsLeftInFirst = firstEnumerator.MoveNext();
}
else
{
yield return secondEnumerator.Current;
elementsLeftInSecond = secondEnumerator.MoveNext();
}
}
}
}
用法:
var s1 = new[] { 1, 3, 5, 7, 9 };
var s2 = new[] { 2, 4, 6, 6, 6, 8 };
var merged = s1.MergeSorted(s2, (a, b) => a > b ? 1 : -1).ToList();
Console.WriteLine(string.Join(", ", merged));
输出:
1, 2, 3, 4, 5, 6, 6, 6, 7, 8, 9
这篇关于有没有一种简单的方法使用LINQ to合并两个有序序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!