简体   繁体   English

根据字符的ascii(或unicode)代码对DataTable进行排序

[英]Sorting a DataTable, based on the ascii (or unicode) code of the characters

I have a DataTable with data in a string column. 我有一个在字符串列中包含数据的DataTable。 Values: "1" "{" "2" 值:“ 1”“ {”“ 2”

When I select data from the DataTable sorting by the column I would like to get the values as: "1" "2" "{" 当我从按列排序的DataTable中选择数据时,我希望获得的值为:“ 1”,“ 2”,“ {”

but instead, I get the values as: "{" "1" "2" 但是相反,我得到的值为:“ {”“ 1”“ 2”

If I needed to do it in sql server I would use the collation "Latin1_general_bin". 如果需要在sql server中执行此操作,则可以使用排序规则“ Latin1_general_bin”。 I need that same behavior in DataTable. 我在DataTable中需要相同的行为。

Here is my test: 这是我的测试:

 [Test]
    public void TestDataTable()
    {
        var dt = new DataTable();
        dt.Columns.Add("a", typeof(string));
        dt.Rows.Add("1");
        dt.Rows.Add("{");
        dt.Rows.Add("2");
        int i = 0;
        foreach (var val in dt.Select("", "a"))
        {
            Assert.AreEqual(new string[] {"1", "2", "{"}[i++],val["a"]);
        }
    }

You can turn the DataTable into an Enumerable and then use OrderBy. 您可以将DataTable变成Enumerable,然后使用OrderBy。 Then use Enumerable.AsDataView().Table. 然后使用Enumerable.AsDataView()。Table。

Might be a bit much, but it should work. 可能很多,但是应该可以。

Cheers, Lior :). 干杯,骗子:)。

The best solution I can come up with at this time is, setting the private field _compareFlags using reflection. 目前,我能想到的最佳解决方案是使用反射设置私有字段_compareFlags。 I know, I hate reflection for this, and it might stop working at some unknown time, but I have a lot of unit tests for it so I hope I will not live to regret this. 我知道,我对此很讨厌,并且它可能会在未知的时间停止工作,但是我对此有很多单元测试,所以我希望我不会为此感到后悔。

Any better solution is welcome, I thought of creating my own culture info, but couldn't see it through (open to suggestions on this path). 我想创建自己的文化信息,但欢迎任何更好的解决方案,但是看不到它(对此路径不建议)。

Here is what I did with reflection: 这是我所做的反思:

 [Test]
    public void TestDataTable()
    {
        var dt = new DataTable();
        var f = typeof (DataTable).GetField("_compareFlags",
                                            System.Reflection.BindingFlags.NonPublic |
                                            System.Reflection.BindingFlags.Instance);

        var v = (System.Globalization.CompareOptions) f.GetValue(dt);
        f.SetValue(dt,  CompareOptions.OrdinalIgnoreCase);



        dt.Columns.Add("a", typeof(string));
        dt.Rows.Add("1");
        dt.Rows.Add("{");
        dt.Rows.Add("2");
        int i = 0;
        foreach (var val in dt.Select("", "a"))
        {
            Assert.AreEqual(new string[] {"1", "2", "{"}[i++],val["a"]);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM