c# - 自定义排序 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; }
}
解决方案
您可以使用Any
andchar.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()
}
推荐阅读
- python - 有没有办法停止从资源组到资源的继承,并使用 python 对 Azure 的虚拟机磁盘应用只读锁?
- visual-studio-code - 即使以管理员身份,Visual Studio Code 也无法保存 ReadOnly 文件
- java - 如何使用 Antlr 在 Java 中获取 .txt 输入文件的解析树
- crafter-cms - 由于 HTTP 和 HTTPS 混合内容,预览未在 Crafter Studio 中加载
- java - 使用 Spring Data JPA 实现策略模式服务层
- javascript - DiscordJS 消息属性“查找”未定义
- three.js - Three.js 从纹理渲染深度
- selenium - 在 selenium 中使用记住的用户模拟网站
- apache-kafka-streams - kafka 流没有从平面地图值向 dlq 主题生成消息
- python - pd.Series - “文件名” KeyError