【问题标题】:How can i sort two dimentional array with linq and with Compareto method?如何使用 linq 和 Compareto 方法对二维数组进行排序?
【发布时间】:2010-06-19 17:07:44
【问题描述】:

如何使用 linq 对 2D 数组进行排序,而不使用 Copareto 对 linq 进行排序。我可以用 list generic 做到这一点。但我不喜欢它。你能给出任何想法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace TestFillArray { class Program { static void Main(string[] args) {

DataTable table = GetTable(); int[,] mySortedLists = new int[table.Rows.Count, table.Columns.Count]; for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < table.Columns.Count; j++) { mySortedLists[i, j] += table.Rows[i][j].ToString().Length; } } List<int> list = new List<int>(); for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < table.Columns.Count; j++) { Console.WriteLine(mySortedLists[i, j].ToString()); list.Add(int.Parse(mySortedLists[i, j].ToString())); } } list.Sort(); list.Reverse(); foreach (int item in list) { Console.WriteLine(item.ToString()); } Console.ReadKey(); } static DataTable GetTable() { // // Here we create a DataTable with four columns. // DataTable table = new DataTable(); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); // // Here we add five DataRows. // table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); return table; } }

}

【问题讨论】:

  • 我不明白一遍又一遍地问相同类型的问题。

标签: c# .net visual-studio visual-studio-2008


【解决方案1】:

你的问题不是很清楚——你有什么样的输入,你想得到什么样的输出?

根据您的示例,您似乎只想将 2D 数组的所有元素作为单个列表获取,然后对元素进行一些操作。要将二维数组转换为包含所有元素的单个 IEnumerable,您可以编写:

IEnumerable<T> AsEnumerable(this T[,] arr) {
  for(int i = 0; i < arr.GetLength(0); i++)
    for(int j = 0; j < arr.GetLength(1); j++)
      yield return arr[i, j];
}

然后写例如:

int[,] data = // get data somwhere
// After 'AsEnumerable' you can use all standard LINQ operations
var res = data.AsEnumerable().OrderBy(n => n).Reverse();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 2013-09-13
    • 1970-01-01
    • 2019-04-14
    • 2013-08-17
    • 2012-08-20
    • 2015-09-17
    相关资源
    最近更新 更多