【问题标题】:C#, How to sort DataTable in a customised order? [closed]C#,如何按自定义顺序对 DataTable 进行排序? [关闭]
【发布时间】:2014-12-02 04:38:55
【问题描述】:

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

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

例如,我在 DataTable 中有一个名为 Animals 的列,具有以下值:

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

我想按自定义顺序对其进行排序,按仓鼠、鸟、猫、狗的升序排列。

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

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

推荐的方法是什么?

【问题讨论】:

  • Sql 查询在您填充 DataTable 的位置是什么样子的。您是否尝试过编写查询、运行它并在必要时重构查询以获得您期望的结果..? Select ColumnName From Table Order by ColumnName Desc 请在如何编写基本 SQL 方面多花点力气在谷歌上搜索,这在本质上并不难
  • 约翰你有SQL Statement 可以与我们其他人分享吗?
  • 由于公司政策,我无法对 SQL 端做任何事情。我必须单独使用填充的 DataTable。

标签: c# .net sorting datatable


【解决方案1】:

由于我没有阅读问题,抱歉,这是一种令人讨厌的做法,但应该可以。

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

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

未测试。

【讨论】:

  • 那是如何按Hamster, Bird, Cat, Dog 顺序排列的?
  • @LittleBobbyTables 如果列是 varchar / nvarchar 类型,它将按字母顺序进行。
  • 膨胀。 Hamster 如何按字母顺序排在 Bird 之前?
  • @LittleBobbyTables 道歉,我应该更仔细地阅读这个问题。稍等片刻就会更新。
【解决方案2】:

对于我的问题,我确实有一个非正统的解决方案,即添加一个新列,该列存储一个与我需要的排序顺序相对应的数字。

例子:

动物:猫、猫、鸟、鸟、狗、狗、仓鼠 排序号:3、3、2、2、4、4、1、1

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

【讨论】:

  • 这不是答案。
【解决方案3】:

虽然我很难找到与此相关的任何文档,但似乎 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)

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 2011-01-08
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多