问题
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