string[] listOne = new string[] { "dog", "cat", "car", "apple"};
string[] listTwo = new string[] { "car", "apple"};
我需要的是按(如果存在)listOne
中的项目顺序进行排序。listTwo
所以新列表将按以下顺序排列:
“汽车”、“苹果”、“狗”、“猫”
您可以使用扩展方法Union()
var result = listTwo.Union<string>(listOne);
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"
由于您使用的是数组,因此 linq 的大部分使用都会创建某种 的新实例IEnumerable
,例如ToList
或ToArray
。
因此,我建议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);
var sub1 = listOne.Intersect(listTwo).ToList();
var sub2 = listOne.Except(listTwo);
sub1.AddRange(sub2);
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();
var result = listOne.Union(listTwo)
.Distinct()
.OrderBy(i => !listTwo.Contains(i));