【问题标题】:Sort 2 dimensional List based on first indexvalue根据第一个索引值对二维列表进行排序
【发布时间】:2014-11-29 14:11:21
【问题描述】:

我已将以下值添加到我的 2D 列表(列表列表)中。它包含水果的重量及其名称。你能告诉我如何根据权重的第一个索引值对这个二维数组进行排序吗?

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# 新手,如果可能的话,请给我一个例子

【问题讨论】:

  • 您应该创建一个自定义类,然后使用该类中的对象列表,而不是使用 2D ArrayList。
  • 感谢您的所有 cmets 和回答。他们都非常乐于助人。

标签: c# arrays list sorting


【解决方案1】:

简单回答:

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

好吧,这是一个真的糟糕的设计,首先因为字符串比较不会给你同样的顺序double比较会。很容易修复:

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

除了现在,如果您输入错误的数字(并且不能解析为双精度数),它将引发异常。您真正想要做的是创建一个“水果”对象:

class Fruit
{
    public string Name { get; set; }
    public double Weight { get; set; }
}

并持有List&lt;Fruit&gt;。现在你可以写了:

matrix.OrderBy(f => f.Weight);

异常没有问题,因为如果你写错了你会得到一个编译时错误。

OrderBy 返回一个 IEnumerable,因此请确保在打印时使用返回值而不是 matrix

【讨论】:

  • @BradleyDotNET 您能否详细解释一下 List 的含义。这是否意味着我应该将我的数组列表重命名为 List&lt;List&lt;Fruit&gt;&gt; matrix = new List&lt;List&lt;Fruit&gt;&gt;(); 在创建一个名为 Fruit 的类之​​后,如您所述
  • @DP。不,单个List&lt;Fruit&gt; 将包含您的数据就好了。不需要“2D”,因为您已将相关数据封装到一个对象中(在本例中为“Fruit”)。
【解决方案2】:

首先,您需要重新设计您的程序并创建一个保存相关数据的类。这将对应于您当前 2D 列表中的“行”。现在,您可以从此类创建对象列表并定义自定义排序进行排序。

请注意,这还有一个额外的好处,即您可以将数字数据视为数字数据,而不是将所有数据视为字符串。

【讨论】:

  • @BradleyDotNET 感谢您的建议。我是来自 Java 的 C# 菜鸟,所以 LINQ 扩展对我来说仍然很陌生。
  • @BradleyDotNET 我可能应该说List。需要去研究C#数据结构对象层次结构。
猜你喜欢
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2022-01-10
相关资源
最近更新 更多