如何在lambda表达式中对long或int数据类型进行排序?

时间:2015-05-27 10:37:24

标签: c# sorting lambda

以下工作正常排序三列,即DateTime和字符串

data = new List<WorkItem<object>>(rows);
//....Add items to list
data.Sort((x, y) =>
{
    int result = DateTime.Compare((DateTime)x.Column1, (DateTime)y.Column1);
    if (result == 0)
        result = string.Compare((string)x.Column2, (string)y.Column2);
    if (result == 0)
        result = string.Compare((string)x.Column3, (string)y.Column3);
    return result;
});

如何在lambda排序表达式中包含long和int数据类型的排序?

以下内容为'long' does not contain a definition for 'Compare'

data.Sort((x, y) =>
{
    int result = DateTime.Compare((DateTime)x.Column1, (DateTime)y.Column1);
    if (result == 0)
        result = string.Compare((string)x.Column2, (string)y.Column2);
    if (result == 0)
        result = string.Compare((string)x.Column3, (string)y.Column3);
    if (result == 0)
        result = long.Compare((long)x.Column15, (long)y.Column15);
    return result;
});

列是通用类型T

2 个答案:

答案 0 :(得分:2)

long类型确实不包含Compare的定义。如果第一个对象低于第二个对象,则比较返回负值,如果它们相等,则返回0,如果第一个对象大于第二个,则比较返回正值。鉴于此,您只需返回两个长值的差值即可。修改后的代码:

data.Sort((x, y) =>
{
int result = DateTime.Compare((DateTime)x.Column1, (DateTime)y.Column1);
if (result == 0)
    result = string.Compare((string)x.Column2, (string)y.Column2);
if (result == 0)
    result = string.Compare((string)x.Column3, (string)y.Column3);
if (result == 0)
    {
        long r = (long)x.Column15 - (long)y.Column15;
        result = r == 0 ? 0 : r < 0 ? -1 : 1;
    }
return result;
});

确保将Column15更改为您需要的任何内容。

答案 1 :(得分:2)

考虑到long不能是null,您可以简单地说:

result = ((long)x.Column15).CompareTo((long)y.Column15);

或者,当有疑问时:

result = Comparer<long>.Default.Compare((long)x.Column15, (long)y.Column15);

适用于所有基本类型以及支持IComparable<>IComparable的所有类型,并正确处理null值。