使用SortCompare对数据表进行排序,并在底部对空值进行排序 [英] Sorting a datatable with a SortCompare and nulls on bottom

查看:187
本文介绍了使用SortCompare对数据表进行排序,并在底部对空值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个我要排序的数据表。这种类型需要使用排序比较,因为我需要处理诸如"1","2"和"> 25"之类的值。作为数字。我需要在多列上对表进行排序,其中一些列将是升序列,其中一些列将是降序列。此外,任何已排序的列都可以包含空值。空值应位于列表的底部。因此,对于行"5","32","> 23","5","32","17",行数为"5"。
"5","12","22","5","32",< null>
"3","99", "104","5",< null>,< null>

当在三列上按升序排序时,将是:
"3"," "99","104","5","12","22","5","32","17"," 5","32","> 23"""5","32",< null>
" 5"< null>,< null>

我有一个排序和比较器工作一个列,但我遇到多列的问题。任何人都可以指出我正确的方向吗?

杰里

Hi,

I have a datatable I want to sort.  This sort needs to use a Sort Compare because I need to handle values like "1", "2", and ">25" as numerics.  I need to sort the table on multiple columns, some of which will be ascending and some of which will be descending.  Also, any of the sorted columns can can contain null values.  The null values should be at the bottom of the list. 

So with the rows
"5", "32", ">23"
"5", "32", "17"
"5", "12", "22"
"5", "32", <null>
"3", "99","104"
"5", <null>, <null>

when sorted ascending on the three columns would be:
"3", "99","104"
"5", "12", "22"
"5", "32", "17"
"5", "32", ">23"
"5", "32", <null>
"5", <null>, <null>

I have the sort and comparer working for a single column, but am having trouble with a multiple columns.  Can anyone point me in the correct direction?

jerry

推荐答案

你能否发布你目前的排序代码?使用。改变它来做你所描述的事情可能相当容易。

通常的"模式"。用于比较多个字段如下所示。显然,这不适合您的特定情况,因为您需要执行一些调用String.Compare的更高级的东西,但是如何构建"打破平局"的想法。具有广泛的适用性。


Could you please post the sort code that you are currently using.  It might be fairly easy to change it to do what you describe.

The usual "pattern" for comparing multiple fields looks like the following.  Obviously, this is not for your particular situation since you need to do something more advanced that call String.Compare, but the ideas how to structure the "tie breaking" have broad applicability.

            public int Compare(DataRow x, DataRow y)
            {
                // Note: Code to handle cases where x == null || y == null omitted.
                // Many applications do not need such code, although it is technically
                // required to satisfy the IComparer<T>.Compare specification.

                int comp;

                comp = string.Compare((string)x["col1"], (string)y["col1"], StringComparison.CurrentCulture);
                if (comp != 0)
                    return comp;

                comp = string.Compare((string)x["col2"], (string)y["col2"], StringComparison.CurrentCulture);
                if (comp != 0)
                    return comp;

                // Repeat above as needed...

                return string.Compare((string)x["colN"], (string)y["colN"], StringComparison.CurrentCulture);
            }







这篇关于使用SortCompare对数据表进行排序,并在底部对空值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆