Working on C#.NET. I have this list:
List<Tuple<string, float>> sort = new List<Tuple<string, float>>();
I want to sort this list by the float value. Eg if the list is like this:
a,45
b,2
s,32
se,83.21
te,84
s3,9.5
f,7
I want it to be sorted in a descending order, like this:
te,84
se,83.21
a,45
s,32
s3,9.5
f,7
b,2
答案 0 :(得分:2)
If you want to sort the list inplace, you can use the Sort
method that takes Comparison<T>
argument.
To sort by the Tuple.Item2
in ascending order, you can use
sort.Sort((a, b) => a.Item2.CompareTo(b.Item2));
To sort in descending order, just swap a
and b
:
sort.Sort((a, b) => b.Item2.CompareTo(a.Item2));
答案 1 :(得分:0)
Here is an easy way to sort the list:
sort = sort.OrderByDescending(s => s.Item2).ToList();
答案 2 :(得分:0)
You wouldn't sort the list - you'd create a new list which contains the same items, but is sorted.
var sorted = sort.OrderByDescending(t => t.Item2).ToList();
答案 3 :(得分:0)
If you don't want to create a new list you can use the IComparer<>
interface to create a customer comparer.
public class MyCompare : IComparer<Tuple<string, float>>
{
public int Compare(Tuple<string, float> x, Tuple<string, float> y)
{
return y.Item2.CompareTo(x.Item2);
}
}
... then you would use it like this ...
sort.Sort(new MyCompare());