排序2维列表基于第一indexvalue [英] Sort 2 dimensional List based on first indexvalue
问题描述
我在添加以下值到我的2D名单(名单列表)。它包含重量水果其次是他们的名字。你能告诉我如何排序权重的第一指标值这个二维数组基地?
I have added following values in to my 2D List (List of Lists). It contains weight of fruits followed by their names. Can you please tell me how can I sort this 2D array base on the first index value of weight?
List<List<String>> matrix = new List<List<String>>();
matrix.Add(new List<String>()); //Adds new sub List
matrix[0].Add("3.256");
matrix[0].Add("Apple");
matrix.Add(new List<String>());
matrix[1].Add("1.236");
matrix[1].Add("Orange");
matrix.Add(new List<String>());
matrix[2].Add("1.238");
matrix[2].Add("Banana");
matrix.Add(new List<String>());
matrix[2].Add("2.658"); //updated This should be matrix[3] instead of 2
matrix[2].Add("Apple");
....
...
..
Console.WriteLine(matrix[0][0]);//This prints out the value 3.256. after sorting it should print out 1.236
我是新的C#和请给我一个例子,如果这是可能的。
I am new to C# and please show me with an example if this is possible
推荐答案
答案很简单:
matrix.OrderBy( l => l[0]);
好吧,这是一个的真正的设计不好,一是因为该字符串比较是的不的要给你一个双击相同的顺序code>比较会。易不足以解决:
Okay, this is a really bad design, first because the string compare is not going to give you the same order a double
compare would. Easy enough to fix:
matrix.OrderBy( l => double.Parse(l[0]));
除了现在它会抛出一个异常,如果你错误地输入一个数字(并且不能被解析成一个双)。您的真正的想要做的是创造一个果的对象:
Except now it will throw an exception if you typed a number incorrectly (and can't be parsed into a double). What you really want to do is create a "Fruit" object:
class Fruit
{
public string Name { get; set; }
public double Weight { get; set; }
}
和持有列表与LT;水果GT;
。现在,你可以写:
And hold a List<Fruit>
. Now you can write:
matrix.OrderBy(f => f.Weight);
使用有例外没有问题,因为如果你写,你会得到一个编译时错误是错误的。
With no problems with exceptions, since you will get a compile time error if you wrote it wrong.
的OrderBy返回一个IEnumerable,所以一定要确保在打印时使用的返回值,而不是矩阵
OrderBy returns an IEnumerable, so make sure you utilize the return value instead of matrix
when printing
这篇关于排序2维列表基于第一indexvalue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!