# .net – 如何使用LINQ执行合并排序？

```Sample input:

lst1 = {5,10,12}
lst2 = {7,9,16,20,25}

result: {5,7,9,10,12,16,20,25}```

for循环解决方案：

```var lst1 = new List<int> { 5, 10, 12 };
var lst2 = new List<int> { 7, 9, 16, 20, 25 };

var result = new List<int>();

int j = 0;
for (int i = 0; i < lst1.Count; i++)
{
while (j < lst2.Count && lst2[j] < lst1[i])
{
j++;
}
}

while (j < lst2.Count)
{
j++;
}
Console.WriteLine(string.Join(",", result.ToArray()));```
LINQ中没有这样的方法.而且我认为不可能将现有的方法结合起来完全按照你想要的方式进行(如果是的话,它会过于复杂).

```static IEnumerable<T> Merge<T>(this IEnumerable<T> first,
IEnumerable<T> second,
Func<T, T, bool> predicate)
{
// validation ommited

using (var firstEnumerator = first.GetEnumerator())
using (var secondEnumerator = second.GetEnumerator())
{
bool firstCond = firstEnumerator.MoveNext();
bool secondCond = secondEnumerator.MoveNext();

while (firstCond && secondCond)
{
if (predicate(firstEnumerator.Current,  secondEnumerator.Current))
{
yield return firstEnumerator.Current;
firstCond = firstEnumerator.MoveNext();
}
else
{
yield return secondEnumerator.Current;
secondCond = secondEnumerator.MoveNext();
}
}

while (firstCond)
{
yield return firstEnumerator.Current;
firstCond = firstEnumerator.MoveNext();
}

while (secondCond)
{
yield return secondEnumerator.Current;
secondCond = secondEnumerator.MoveNext();
}
}
}```

`lst1.Merge(lst2, (i, j) => i < j)`