Sort 2 dimensional List based on first indexvalue

北战南征 提交于 2020-01-16 04:53:08

问题


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

I am new to C# and please show me with an example if this is possible


回答1:


Simple answer:

matrix.OrderBy( l => l[0]);

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; }
}

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 returns an IEnumerable, so make sure you utilize the return value instead of matrix when printing




回答2:


First of all, you need to redesign your program and create a class which holds the related data. This will correspond to a "row" in your current 2D list. Now you can create an list of objects from this class and define a custom ordering for sorting.

Note that this has the added benefit that you can treat numeric data as such rather than treating all data as Strings.



来源:https://stackoverflow.com/questions/26197230/sort-2-dimensional-list-based-on-first-indexvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!