C#,如何按照自定義順序對DataTable進行排序?C#,如何按照自定義順序對DataTable進行排序?
我有一個DataTable已經充滿了數據,我該如何按自定義的順序對它進行排序?
例如,我在數據表叫動物具有以下值的列:
貓,貓,鳥,鳥,狗,狗,倉鼠,倉鼠
我想它在排序按照倉鼠,鳥,貓,狗的升序排列的定製訂單。
所以我根據我上面的例子中輸出應該是:
倉鼠,倉鼠,鳥,鳥,貓,貓,狗,狗
什麼是推薦的方式做到這一點?
C#,如何按照自定義順序對DataTable進行排序?C#,如何按照自定義順序對DataTable進行排序?
我有一個DataTable已經充滿了數據,我該如何按自定義的順序對它進行排序?
例如,我在數據表叫動物具有以下值的列:
貓,貓,鳥,鳥,狗,狗,倉鼠,倉鼠
我想它在排序按照倉鼠,鳥,貓,狗的升序排列的定製訂單。
所以我根據我上面的例子中輸出應該是:
倉鼠,倉鼠,鳥,鳥,貓,貓,狗,狗
什麼是推薦的方式做到這一點?
由於我沒有讀過這個問題,道歉,這是一個討厭的方式,但應該工作。
DataTable dt = YOURTABLE.Select("Animals == 'Hamster'").CopyToDataTable();
DataTable dt2 = YOURTABLE.Select("Animals != 'Hamster'").CopyToDataTable();
dt2 = dt2.Sort = "Animals + " " + "Asc";
dt.Merge(dt2);
YOURTABLE = dt;
未測試。
那麼在「倉鼠,鳥,貓,狗」命令中,這種排序呢? – LittleBobbyTables 2014-10-07 17:06:38
@LittleBobbyTables如果列的類型是varchar/nvarchar,它將按字母順序執行。 – 2014-10-07 17:07:30
膨脹。 「倉鼠」如何按照字母順序出現在「鳥」之前? – LittleBobbyTables 2014-10-07 17:08:03
雖然我很難找到任何文檔來達到這種效果,但看起來好像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)
我有一個非正統的解決我的問題,就是通過增加一個新的列,其門店與我需要的排序順序相對應的數字。
實施例:
動物:貓,貓,鳥,鳥,狗,狗,倉鼠 SortNumber:3,3,2,2,4,4,1,1
哪個是可能是最簡單的方法。但我希望有一個更合適的解決方案。
這不是一個答案。 – dannmate 2014-10-08 05:44:47
Sql查詢看起來像在填充DataTable的位置。您是否試過編寫查詢,運行它並在必要時重構查詢以獲取您期望的結果..? '選擇ColumnName從Table Order by ColumnName Desc'請顯示更多的努力還谷歌如何編寫基本的SQL這不是那麼困難的性質 – MethodMan 2014-10-07 17:02:03
約翰你有'SQL語句',你可以與我們其他人分享..? – MethodMan 2014-10-07 17:09:24
由於公司政策,我無法對SQL端進行任何操作。我必須單獨使用填充的DataTable。 – 2014-10-07 17:21:57