问题
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.
回答1:
If you have a list of Tuples you could order them like this
myList.OrderBy(x => x.Item2);
回答2:
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.)
回答3:
.NET has a SortedDictionary data type.
http://msdn.microsoft.com/en-us/library/f7fta44c%28v=vs.90%29.aspx
I would just load them into that and you should be good.
回答4:
I would create a small "pair" class, with a string and integer property. You can implement IComparable() to ensure that this class gets compared by the Integer property. You can then stuff them into a generic List: var pairs = new List<Pair>()
object, and use the sort method to sort them: pairs.Sort();
.
来源:https://stackoverflow.com/questions/13144006/identically-sorting-two-lists