Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

c# - Sort a list according to another list

I have a list1 like this :

{A,B,C,D,E,F}

I have another list2 that list2 count is equal with list1 count (6=6) :

{50,100,14,57,48,94}

I want sort list1 according to list2, that list2 to be sorted ascending.

{14,48,50,57,94,100}

as a result :

{C,E,A,D,F,B}

I used the following code. But the result is not sorted

list1= list1.OrderBy(d => list2.IndexOf(d)).ToList();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not use a sorted dictionary?

var list1 = new List<int> { 50, 100, 14, 57, 48, 94 }
var list2 = new List<string> { "A", "B", "C", "D", "E", "F" };
var dict = new SortedDictionary<int, string>();

for (int i = 0; i < list1.Count; i++)
{
   dict.Add(list1[i], list2[i]);
}

You'll now be able to access the values in the correct order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...