首页 > 解决方案 > 自定义排序 LINQ C#

问题描述

我有对象列表。我正在尝试使用其中一个属性对其进行排序。

我正在尝试以下内容:

items.OrderBy(x => x.Name).ToList()

items 可以包含 Name 的值,如下所示:

case 1 - abc,xyz,byc,myu
case 2 - abc3,xur2,iuy7

如果任何值包含 int(数字),我想按降序对列表进行排序。所以在案例2中,我想按降序排序。在情况 1 中,排序将按升序排列。问题是如何识别列表是否包含任何整数?这样我就可以决定订购。

public class TestClass
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

标签: c#

解决方案


您可以使用Anyandchar.IsDigit来确定是否存在:

if(items.Any(x => x.Name.Any(char.IsDigit)))
{
    // descending  
    items = items.OrderByDescending(x => x.Name)).ToList()
}
else
{
    // ascending
    items = items.OrderBy(x => x.Name)).ToList()
}

推荐阅读