按另一个字符串列表对字符串列表进行排序

时间:2015-02-26 13:51:35

标签: c# linq sorting

我有一个字符串列表,我希望按另一个字符串列表排序,如果列表中有不在比较器列表中的项目,我想要它们,因为它们位于列表的末尾。我怎么能这样做?

所以如果我有这个清单:List<string> {"A","T","G","F","V","E","W","Q" }
我有一个比较器:List<string> {"T","F","V","A" }
我希望结果为:List<string> {"T","F","V","A","G","E","W","Q" }

谢谢!

4 个答案:

答案 0 :(得分:6)

您似乎需要使用IntersectExcept,例如:

List<string> originalList = new List<string> {"A", "T", "G", "F", "V", "E", "W", "Q"};
List<string> compareList = new List<string> {"T", "F", "V", "A"};

var intersectedItems = compareList.Intersect(originalList);
var notIntersectedItems = originalList.Except(compareList);
var resultList = intersectedItems.Concat(notIntersectedItems).ToList();

你会得到:

resultList = T,F,V,A,G,E,W,Q

答案 1 :(得分:6)

如果List<T>.IndexOf返回int.Maxvalue,您可以使用-1并使用List<string> result = list.OrderBy(str => { int index = comparer.IndexOf(str); return index == -1 ? int.MaxValue : index; }).ToList();

ThenBy(x => x.String)

这是一个长版本,对某些人来说可能更具可读性。它也更灵活,因为您可以指定不包含项目的内容。例如,您可以通过在Select(x => x.String)之前添加List<string> result = list.Select(str => new { ComparerIndex = comparer.IndexOf(str), String = str }) .OrderBy(x => x.ComparerIndex == -1 ? 1 : 0) // not contained -> at the end .ThenBy(x => x.ComparerIndex) .Select(x => x.String) .ToList(); 来按字典顺序排序:

{{1}}

答案 2 :(得分:2)

这应该这样做:

var a = new List<string> {"A","T","G","F","V","E","W","Q" };
var b = new List<string> {"T","F","V","A"};

var res = b.Concat(a.Except(b));

答案 3 :(得分:0)

List<string> input = new List<string> { "A", "T", "G", "F", "V", "E", "W", "Q" };
List<string> input1 = new List<string> { "T", "F", "V", "A" };
var res = input.Union(input1).OrderBy(c => c).ToList();