2014-10-07 391 views
-5

C#,如何按照自定义顺序对DataTable进行排序?C#,如何按照自定义顺序对DataTable进行排序?

我有一个DataTable已经充满了数据,我该如何按自定义的顺序对它进行排序?

例如,我在数据表叫动物具有以下值的列:

猫,猫,鸟,鸟,狗,狗,仓鼠,仓鼠

我想它在排序按照仓鼠,鸟,猫,狗的升序排列的定制订单。

所以我根据我上面的例子中输出应该是:

仓鼠,仓鼠,鸟,鸟,猫,猫,狗,狗

什么是推荐的方式做到这一点?

+3

Sql查询看起来像在填充DataTable的位置。您是否试过编写查询,运行它并在必要时重构查询以获取您期望的结果..? '选择ColumnName从Table Order by ColumnName Desc'请显示更多的努力还谷歌如何编写基本的SQL这不是那么困难的性质 – MethodMan 2014-10-07 17:02:03

+0

约翰你有'SQL语句',你可以与我们其他人分享..? – MethodMan 2014-10-07 17:09:24

+0

由于公司政策,我无法对SQL端进行任何操作。我必须单独使用填充的DataTable。 – 2014-10-07 17:21:57

回答

2

由于我没有读过这个问题,道歉,这是一个讨厌的方式,但应该工作。

DataTable dt = YOURTABLE.Select("Animals == 'Hamster'").CopyToDataTable(); 
DataTable dt2 = YOURTABLE.Select("Animals != 'Hamster'").CopyToDataTable(); 

dt2 = dt2.Sort = "Animals + " " + "Asc"; 
dt.Merge(dt2); 
YOURTABLE = dt; 

未测试。

+1

那么在“仓鼠,鸟,猫,狗”命令中,这种排序呢? – LittleBobbyTables 2014-10-07 17:06:38

+0

@LittleBobbyTables如果列的类型是varchar/nvarchar,它将按字母顺序执行。 – 2014-10-07 17:07:30

+1

膨胀。 “仓鼠”如何按照字母顺序出现在“鸟”之前? – LittleBobbyTables 2014-10-07 17:08:03

0

虽然我很难找到任何文档来达到这种效果,但看起来好像DataTable类本身是顺序不可知的 - 也就是说,它会按照它们加载的顺序呈现记录(在这种情况下通过适配器加载的DataTable,这将是结果集中行的顺序)。

可以按特定的排序顺序(如此处所示:Sorting rows in a data table)提取记录,并创建一个新的DataTable以及新的序列中的行。这似乎是大多数人获得某种效果的方式。

然而Select方法接受它的排序条件作为一个字符串(http://msdn.microsoft.com/en-us/library/way3dy9w(v=vs.110).aspx),这意味着排序条件仅限于类支持的排序条件。所有支持的文档都是列名和方向。

既然你想要的是一个自定义的分类,而不是一个基本的列,它会显示基地DataTable没有处理这个内置的机制。我想在你的场景中需要的是编写一些代码来从DataTable中提取记录,使用自定义分类器对它们进行排序(使用LINQ的OrderBy,对提取的数据使用函数可能会做到这一点),然后插入他们成为您的代码继续使用的新的DataTable

由于这种方法的一个例子:

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

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DataTable inputDataTable = CreateInputDataTable(); 
      Console.WriteLine("Input data table: "); 
      PrintDataTable(inputDataTable); 
      DataTable outputDataTable = CustomSortDataTable(inputDataTable); 
      Console.WriteLine("Sorted data table: "); 
      PrintDataTable(outputDataTable); 
     } 

     private static DataTable CustomSortDataTable(DataTable inputDataTable) 
     { 
      DataRow[] rows = inputDataTable.Select(); 
      IComparer<string> animalTypeComparer = new AnimalTypeComparer(); 

      IEnumerable<DataRow> sortedRows = rows.OrderBy(x => x["AnimalType"].ToString(), animalTypeComparer); 

      DataTable result = new DataTable(); 

      result.Columns.Add("ID"); 
      result.Columns.Add("AnimalType"); 

      foreach(DataRow row in sortedRows) 
      { 
       result.ImportRow(row); 
      } 

      return result; 
     } 

     private static void PrintDataTable(DataTable inputDataTable) 
     { 
      foreach(DataRow row in inputDataTable.Rows) 
      { 
       Console.WriteLine("({0}, {1})", row["ID"], row["AnimalType"]); 
      } 
     } 

     private static DataTable CreateInputDataTable() 
     { 
      DataTable result = new DataTable(); 

      result.Columns.Add("ID"); 
      result.Columns.Add("AnimalType"); 

      DataRow toInsert = result.NewRow(); 

      toInsert["ID"] = 1; 
      toInsert["AnimalType"] = "Cat"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 2; 
      toInsert["AnimalType"] = "Cat"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 3; 
      toInsert["AnimalType"] = "Bird"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 4; 
      toInsert["AnimalType"] = "Bird"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 5; 
      toInsert["AnimalType"] = "Dog"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 6; 
      toInsert["AnimalType"] = "Dog"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 7; 
      toInsert["AnimalType"] = "Hamster"; 
      result.Rows.Add(toInsert); 

      toInsert = result.NewRow(); 
      toInsert["ID"] = 8; 
      toInsert["AnimalType"] = "Hamster"; 
      result.Rows.Add(toInsert); 

      return result; 
     } 
    } 

    class AnimalTypeComparer : IComparer<string> 
    { 
     private static readonly string[] AnimalTypes = {"Hamster", "Bird", "Cat", "Dog"}; 
     #region Implementation of IComparer<in string> 

     /// <summary> 
     /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. 
     /// </summary> 
     /// <returns> 
     /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown in the following table.Value Meaning Less than zero<paramref name="x"/> is less than <paramref name="y"/>.Zero<paramref name="x"/> equals <paramref name="y"/>.Greater than zero<paramref name="x"/> is greater than <paramref name="y"/>. 
     /// </returns> 
     /// <param name="x">The first object to compare.</param><param name="y">The second object to compare.</param> 
     public int Compare(string x, string y) 
     { 
      return Array.IndexOf(AnimalTypes, x).CompareTo(Array.IndexOf(AnimalTypes, y)); 
     } 

     #endregion 
    } 
} 

运行此打印出以下几点:

Input data table: 
(1, Cat) 
(2, Cat) 
(3, Bird) 
(4, Bird) 
(5, Dog) 
(6, Dog) 
(7, Hamster) 
(8, Hamster) 
Sorted data table: 
(7, Hamster) 
(8, Hamster) 
(3, Bird) 
(4, Bird) 
(1, Cat) 
(2, Cat) 
(5, Dog) 
(6, Dog) 
0

我有一个非正统的解决我的问题,就是通过增加一个新的列,其门店与我需要的排序顺序相对应的数字。

实施例:

动物:猫,猫,鸟,鸟,狗,狗,仓鼠 SortNumber:3,3,2,2,4,4,1,1

哪个是可能是最简单的方法。但我希望有一个更合适的解决方案。

+0

这不是一个答案。 – dannmate 2014-10-08 05:44:47

相关问题