How can i sort two dimentional array with linq and with Compareto method?
How can i sort 2D array with linq and without linq with Copareto . i can do that with list generic . But i dislike it. can you give any idea about it?
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));
//
// He开发者_StackOverflowre 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;
}
}
}
Your question isn't very clear - what kind of input do you have and what output do you want to get as the result?
Based on your example, it seems that you simply want to get all elements of 2D array as a single list and then do some operation with the elements. To convert 2D array to a single IEnumerable
containing all the elements, you can write:
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];
}
And then write for example:
int[,] data = // get data somwhere
// After 'AsEnumerable' you can use all standard LINQ operations
var res = data.AsEnumerable().OrderBy(n => n).Reverse();
精彩评论