首页 \ 问答 \ 自然排序为Datgridview(Natural Sort for Datgridview)

自然排序为Datgridview(Natural Sort for Datgridview)

我有一个数据网格列,允许用户输入可能包含数字的字符串。 我已经做了编程排序的列和另一个自动排序的列。 我查看了关于这个网站和其他网站的所有可用信息,但没有发现任何可行的或在某些情况下我能够知道如何实施的信息。 许多解决方案都使用Icomparer,但很少有解决方案专门用于datagridview。 这是执行datagridview1.Sort(Column1,ListSortDirection.Ascending)后列数据的一个示例;

1
140
2b
40
70
7a
9
aa
aa30
aa5
bc
de

我已经介绍了MyDatagridHelper类和使用本站点解决方案的相关代码: C#:自定义排序的DataGridView ,但它提供了以下结果

aa
bc
de
aa30
2b
7a
70
1
40
140
9
aa5

所有其他解决方案不是特定于datagridview。 我是自学成才,对编码相对较新,所以我无法理解其中的代码。 我尽可能地尝试找到共同点,并剪切和粘贴,但无济于事。 我认为有些例子显示了承诺并可能完成这项工作: https : //www.codeproject.com/articles/22517/natural-sort-comparerC#中的自然排序顺序

我如何实施这些或其他任何可能完成这项工作的解决方案都需要帮助。 由于与问题无关,我没有将第二列简单加入。 谢谢


I have a datagrid with a column that allows entry by the user of strings which may contain numbers. The column I have made sorted programmatically and one other automatically. I have looked at all available information on this and other websites but have found nothing that works or in some cases that I am able to know how to implement. Many of the solutions use Icomparer but few are specifically for datagridview. This is an example of the column data after performing datagridview1.Sort(Column1, ListSortDirection.Ascending);

1
140
2b
40
70
7a
9
aa
aa30
aa5
bc
de

I have introduced the MyDatagridHelper Class and relevant code using the solution from this site: C#: Custom sort of DataGridView, but alas it gives the following results

aa
bc
de
aa30
2b
7a
70
1
40
140
9
aa5

All other solutions are not specific to datagridview. I am self taught and relatively new to coding, so I am not able to make sense of the code within. I have tried as best I can to find commonality and cut and paste but to no avail. Some examples I thought showed promise and might do the job were: https://www.codeproject.com/articles/22517/natural-sort-comparer and Natural Sort Order in C#

I effectively need help on how to implement these or any other solutions that might do the job. I have not included the second column for simplicity as it is not relevant to the question. Thanks


原文:https://stackoverflow.com/questions/41239449
更新时间:2019-06-21 02:04

最满意答案

您链接到的代码项目文章22517具有您需要的逻辑,只需通过创建System.Collections.IComparer实现而不是System.Collections.Generic.Comparer调整DataGridView的使用方式

所以如果你在你的项目中创建一个新的类,就像这样:

public class NaturalSortComparer : System.Collections.IComparer {

    private System.Collections.Generic.Dictionary<string, string[]> table;

    public NaturalSortComparer() {
        table = new System.Collections.Generic.Dictionary<string, string[]>();
    }

    public void Dispose() {
        table.Clear();
        table = null;
    }

    public int Compare(object x, object y) {
        System.Windows.Forms.DataGridViewRow DataGridViewRow1 = (System.Windows.Forms.DataGridViewRow)x;
        System.Windows.Forms.DataGridViewRow DataGridViewRow2 = (System.Windows.Forms.DataGridViewRow)y;

        string xStr = DataGridViewRow1.Cells["Column1"].Value.ToString();
        string yStr = DataGridViewRow2.Cells["Column1"].Value.ToString();


        if (xStr == yStr) {
            return 0;
        }
        string[] x1, y1;
        if (!table.TryGetValue(xStr, out x1)) {
            x1 = System.Text.RegularExpressions.Regex.Split(xStr.Replace(" ", ""), "([0-9]+)");
            table.Add(xStr, x1);
        }
        if (!table.TryGetValue(yStr, out y1)) {
            y1 = System.Text.RegularExpressions.Regex.Split(yStr.Replace(" ", ""), "([0-9]+)");
            table.Add(yStr, y1);
        }

        for (int i = 0; i < x1.Length && i < y1.Length; i++) {
            if (x1[i] != y1[i]) {
                return PartCompare(x1[i], y1[i]);
            }
        }
        if (y1.Length > x1.Length) {
            return 1;
        } else if (x1.Length > y1.Length) {
            return -1;
        } else {
            return 0;
        }
    }

    private static int PartCompare(string left, string right) {
        int x, y;
        if (!int.TryParse(left, out x)) {
            return left.CompareTo(right);
        }

        if (!int.TryParse(right, out y)) {
            return left.CompareTo(right);
        }

        return x.CompareTo(y);
    }
}

你可以在这里看到,我已经硬编码它使用名为“Column1”的列作为你的例子,但你可以改变这是更动态。

当你对网格进行排序时,你可以传入你刚创建的这个类的新实例,如下所示:

dataGridView1.Sort(new NaturalSortComparer());

The code project article 22517 that you link to has the logic in there that you require, it just needs some tweaking for use with a DataGridView by creating an implementation of System.Collections.IComparer rather than System.Collections.Generic.Comparer

So if you create yourself a new class in your project something like this:

public class NaturalSortComparer : System.Collections.IComparer {

    private System.Collections.Generic.Dictionary<string, string[]> table;

    public NaturalSortComparer() {
        table = new System.Collections.Generic.Dictionary<string, string[]>();
    }

    public void Dispose() {
        table.Clear();
        table = null;
    }

    public int Compare(object x, object y) {
        System.Windows.Forms.DataGridViewRow DataGridViewRow1 = (System.Windows.Forms.DataGridViewRow)x;
        System.Windows.Forms.DataGridViewRow DataGridViewRow2 = (System.Windows.Forms.DataGridViewRow)y;

        string xStr = DataGridViewRow1.Cells["Column1"].Value.ToString();
        string yStr = DataGridViewRow2.Cells["Column1"].Value.ToString();


        if (xStr == yStr) {
            return 0;
        }
        string[] x1, y1;
        if (!table.TryGetValue(xStr, out x1)) {
            x1 = System.Text.RegularExpressions.Regex.Split(xStr.Replace(" ", ""), "([0-9]+)");
            table.Add(xStr, x1);
        }
        if (!table.TryGetValue(yStr, out y1)) {
            y1 = System.Text.RegularExpressions.Regex.Split(yStr.Replace(" ", ""), "([0-9]+)");
            table.Add(yStr, y1);
        }

        for (int i = 0; i < x1.Length && i < y1.Length; i++) {
            if (x1[i] != y1[i]) {
                return PartCompare(x1[i], y1[i]);
            }
        }
        if (y1.Length > x1.Length) {
            return 1;
        } else if (x1.Length > y1.Length) {
            return -1;
        } else {
            return 0;
        }
    }

    private static int PartCompare(string left, string right) {
        int x, y;
        if (!int.TryParse(left, out x)) {
            return left.CompareTo(right);
        }

        if (!int.TryParse(right, out y)) {
            return left.CompareTo(right);
        }

        return x.CompareTo(y);
    }
}

You can see in here that I have hard coded it to used a column named "Column1" as per your example, but you can change this to be more dynamic.

When you then sort your grid, you can pass in a new instance of this class you have just created, like this:

dataGridView1.Sort(new NaturalSortComparer());
2016-12-21

相关问答

更多

如何对NSArray进行自然排序?(How to do a natural sort on an NSArray?)

NSString s可以使用NSNumericSearch比较选项进行比较。 一个版本: NSInteger sort(Obj* a, Obj* b, void*) { return [[a title] compare:[b title] options:NSNumericSearch]; } result = [array sortedArrayUsingFunction:&sort context:nil]; 或者更通用: NSInteger sort(id a, id b, v ...

写一个更好的自然排序(比我的)(Writing a better natural sort (than mine))

这已经在Windows中可用,当在浏览器窗口中排列文件时,shell使用自然排序顺序。 至少从Windows 2000开始,它使用的比较函数被导出并可供任何程序使用。尽管P / Invoke并不是最好的解决方案,但它在过去的10多年中经过了数十亿次的测试,具有相当大的优势。 并按照用户已熟悉的方式对字符串进行排序。 处理变音符已经是.NET的一部分,string.Normalize()方法负责处理它。 下面是一个使用它的示例程序,它按原始线程中的请求对字符串进行了正确排序: using Syste ...

排序数组元素(带数字的字符串),自然排序(Sort Array Elements (string with numbers), natural sort)

这被称为“自然排序”,可以像这样在JS中实现: function naturalCompare(a, b) { var ax = [], bx = []; a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) }); b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infin ...

当我们谈论分拣时,什么是自然排序?(what is natural ordering when we talk about sorting?)

自然排序是一种对人类来说似乎很自然的字母数字排序。 在经典的字母数字排序中,我们将会有这样的内容: 1 10 11 12 2 20 21 3 4 5 6 7 如果您使用自然排序,它将是: 1 2 3 4 5 6 7 10 11 12 20 21 根据不同的语言,自然排序有时会忽略大写字母并加以强调(即所有加重的字母都被视为非加重的字母)。 许多语言都有一个函数来自然地排序字符串。 然而,员工对于语言来说太“高级”了,您必须决定自然而然地订购它们意味着什么,并创建相应的功能。 以我的观点来看,订 ...

ruby sort_by两次(ruby sort_by twice)

我会建议把你想排序的列放入数组中。 entries.sort_by { |l| [l.project.name, l.project.time] } 这将尊重每种类型的自然排序顺序。 I would suggest putting the column you want to sort by into an array. entries.sort_by { |l| [l.project.name, l.project.time] } This will respect the natural ...

c++中sort()排序如何使用?

sort是STL中的函数,如何使用要看你用的什么容器。你要包数组中的元素先导入容器中,如vector,list等。然后象调用一般的类方法一样使用。sort()的实现方法要看你的STL的实现版本。用的是用快速排序,有的是用intro排序。快速排序的一般复杂度为nlogn,最差情况为n2。 intro排序复杂度始终为nlogn。

使用.sort与PyMongo(Using .sort with PyMongo)

sort应该是键方向对的列表,也就是 db.test.find({"number": {"$gt": 1}}).sort([("number", 1), ("date", -1)]) 为什么这必须是一个列表的原因是,这些参数的顺序是重要的,而且在Python中并没有排序。 sort should be a list of key-direction pairs, that is db.test.find({"number": {"$gt": 1}}).sort([("number", 1), ( ...

linux sort排序问题

filename="test.txt" sed -n '1p' "$filename" sed -n '2,${/^[a-zA-Z]/p}' "$filename" | sort sed -n '2,${/^\//p}' "$filename" | sort以上脚本对文本文件test.txt按上述要求排序输出

相关文章

更多

最新问答

更多
  • Android宽度:100%修复(网站接管问题)(Android width:100% fix (website takeover issue))
  • C ++函数/方法设计的良好实践(Good practice in C++ function/method design)
  • 计算其他表中不存在的所有记录 - SQL查询(Count all records that does not exist to other table - SQL Query)
  • 为什么我要用JPA共享ID?(Why do I get shared Ids with JPA?)
  • asp.net - 如何显示来自html格式的数据行的字段(asp.net - how to display a field from data row that is in html format)
  • 我们如何使用ActiveRecord从连接表中删除行?(How can we delete rows from a join table by using ActiveRecord?)
  • ng-class搞乱了类的顺序(ng-class messing with the order of classes)
  • oracle 12g无效数字错误(oracle 12g invalid number error)
  • 更改ng-src值onclick(Change ng-src value onclick)
  • 如何在android中自动添加自定义依赖项以创建新项目?(How to add custom dependencies automatically in android for ever a new project is created?)
  • datetime函数在PHP中(datetime function in php)
  • 在javascript中获取会话数组的值(in javascript get the value of a session array)
  • 如何在UTF8中编译LaTeX?(How can I compile LaTeX in UTF8? [closed])
  • Rspec:“array.should == another_array”,但不用担心订单(Rspec: “array.should == another_array” but without concern for order)
  • Logcat错误:无法在android片段中加载视图(Logcat error: unable to load view in android fragments)
  • JavaFX的。(JavaFX. Adding items to the list in different threads is not working)
  • 从GDATA日历资源迁移到Google Calendar Resource api(Migrate from GDATA calendar resource to Google Calendar Resource api)
  • SSRS 2008 - 以零情景处理分割(SSRS 2008 - Dealing with division by zero scenarios)
  • 我如何以编程方式添加一个listView列标题的点击事件(How can I add a listView column header a click event programmatically)
  • Wxpython:无法检索有关列表控件项XXX的信息(Wxpython: Couldn't retrieve information about list control item XXX)
  • 使用Tortoise SVN在SVN存储库中移动目录(Move Directory across SVN repository using Tortoise SVN)
  • 天蓝色服务结构集群中的web api无状态服务是否在一段时间不活动后进入休眠状态?(Do web api stateless services in azure service fabric cluster go to sleep after a period of inactivity?)
  • 我可以设置intelliJ来突出显示PHP编码风格吗?(Can I set intelliJ to highlight php coding style?)
  • 用javafx创建一个Truetype字体文件(Creating a Truetype Font file with javafx)
  • Spring ftp配置错误(Spring ftp configuration is wrong)
  • 使用gsub去除多个字符(Using gsub to strip multiple characters)
  • 续订推送证书并保持当前的App Store App正常工作(Renew Push certificate and keep current App Store App working)
  • js:ES5和ES6之间关于'this'关键字用法的一个令人困惑的观点(js: one confusing point about 'this' keyword usage between ES5 and ES6)
  • window.onload vs $(document).ready()(window.onload vs $(document).ready())
  • 在Swift中,如何声明一个符合一个或多个协议的特定类型的变量?(In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?)