如何排序两个列表

时间:2014-03-21 14:57:12

标签: c#-4.0 c#-3.0

我有两个列表,一个是字符串列表,一个是整数列表。如何对整数List进行排序,还对字符串List进行排序?这两个列表彼此相关。

for example:
   listB.Add(0)
   listB.Add(3)
   listB.Add(2)

   ListA.Add("name1")
   listA.Add("name3")
   listA.Add("name2")

after sorted on the Integer List, the new List should look like below:
   ListB = 0, 2, 3
   LISTA = "name1", "name2", "name3"

2 个答案:

答案 0 :(得分:2)

为什么有列表而不是词典 OrderBy(x => x.Key)

Dictionary<int,string> dict = new Dictionary<int,string>();
dict.Add(0,"name1");
dict.Add(1,"name2");
dict.Add(2,"name3");
var result = dict.OrderBy(x=>x.Key);

答案 1 :(得分:1)

您可以将两者都转换为数组,然后调用Array.Sort(Array keys, Array items, int Index, int Length)。例如:

var a1 = listB.ToArray();
var a2 = listA.ToArray();
Array.Sort(a1, a2, 0. a1.Length);
listA = new List<string>(a2);
listB = new List<int>(a1);

另一种选择是Zip他们并排序:

var sorted = a1.Zip(a2, (first, second) => new { Key = first, Value = second })
               .OrderBy(s => s.Key)
               .ToList();

// now recreate the lists
listB = sorted.Select(s => s.Key).ToList();
listA = sorted.Select(s => s.Value).ToList();