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
269 views
in Technique[技术] by (71.8m points)

c# - Identically sorting two lists

I have on list of strings, and one list of integers. They come in "pairs", i.e. at an index, the given string and integer must still be "matched up". I need to sort the integers in descending order and have the strings sort identically, so the pairs are intact. I imagine the best way to achieve may be to just put them into List>, but I'm not sure how that could be sorted by the second Tuple item.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The easiest way is to put them into a single List, and then order that list:

List<string> list = new List<string>() { "A", "C", "T", "F" };
List<int> list2 = new List<int>() { 5, 4, 3, 2 };

var results = list.Zip(list2, (a, b) => new
{
    str = a,
    num = b
})
.OrderBy(pair=> pair.num);

If you really need a list of just the strings you could use a Select to get them back out, but hopefully it just makes sense to have a single list of a more complex object throughout your program. (Consider making an actual class, rather than using an anonymous one, if you do that.)


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

...