﻿ c# – 有没有一种简单的方法可以使用LINQ合并两个有序序列？ - 代码日志

c# – 有没有一种简单的方法可以使用LINQ合并两个有序序列？

``````IEnumerable<T> first;
IEnumerable<T> second;
``````

``````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
``````