Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...