1
string[] listOne = new string[] { "dog", "cat", "car", "apple"};
string[] listTwo = new string[] { "car", "apple"};

我需要的是按(如果存在)listOne中的项目顺序进行排序。listTwo所以新列表将按以下顺序排列:

“汽车”、“苹果”、“狗”、“猫”

4

6 回答 6

3

您可以使用扩展方法Union()

var result = listTwo.Union<string>(listOne);
于 2013-05-27T03:57:47.073 回答
3
var result = listTwo.Union(listOne);

或者

var result =listTwo.Intersect(listOne).Concat(listOne.Except(listTwo));
var result = listTwo.Where(listOne.Contains).Concat(listOne.Except(listTwo));

发布的第一个答案有listTwo项目顺序错误,请忽略以下答案

var result = listOne.OrderBy(i => !listTwo.Contains(i)).ToList();

结果

"car", "apple", "dog", "cat"
于 2013-05-27T03:58:45.970 回答
2

由于您使用的是数组,因此 linq 的大部分使用都会创建某种 的新实例IEnumerable,例如ToListToArray

因此,我建议Array.Sort比较一起使用:

string[] listOne=new string[] { "dog", "cat", "car", "apple" };
string[] listTwo=new string[] { "car", "apple" };

Comparison<String> comparison=
    (x, y) => {
        if(!listTwo.Contains(x)||!listTwo.Contains(y))
            return 0;
        else {
            var indexOfX=Array.IndexOf(listTwo, x);
            var indexOfY=Array.IndexOf(listTwo, y);
            return indexOfX.CompareTo(indexOfY);
        }
    };

Array.Sort(listOne, comparison);

它将在内部使用快速排序算法进行排序,它是一种就地算法

于 2013-05-27T04:25:44.070 回答
2
var sub1 = listOne.Intersect(listTwo).ToList();
var sub2 = listOne.Except(listTwo); 
sub1.AddRange(sub2);

在此处输入图像描述

于 2013-05-27T03:44:25.523 回答
0

This works, but I have a feeling it could be done better:

var result=
    from item in listOne
    let existsInListTwo=listTwo.Contains(item)
    let positionInListTwo=Array.IndexOf(listTwo, item)
    orderby !existsInListTwo, positionInListTwo
    select new {
        Item=item,
        position=positionInListTwo,
        exists=existsInListTwo
    };

Edit: Using a combination of this and Damith's approach this is a little more readable:

var result=
    listOne.OrderBy(i => !listTwo.Contains(i))
           .ThenBy(i => Array.IndexOf(listTwo, i))
           .ToList();
于 2013-05-27T03:51:17.380 回答
0
var result = listOne.Union(listTwo)
            .Distinct()
            .OrderBy(i => !listTwo.Contains(i));
于 2013-05-27T04:27:10.853 回答