c# - 基于字符串属性值的 List 上的自定义 OrderBy
问题描述
我有以下课程:
public class Document
{
public string DocumentSection { get; set; }
public string DocumentName { get; set; }
}
我想根据 DocumentSection 属性订购以下列表:
List<Document> documents = new List<Document>();
documents.Add(new Document { DocumentSection = "Section One", DocumentName = "doc1" });
documents.Add(new Document { DocumentSection = "Section Two", DocumentName = "doc1123" });
documents.Add(new Document { DocumentSection = "Section Three", DocumentName = "doc113" });
documents.Add(new Document { DocumentSection = "Section Four", DocumentName = "doc123" });
documents.Add(new Document { DocumentSection = "Section Five", DocumentName = "doc11" });
理论上我知道我应该实现 IComparer 来获得它,但这就是困难所在,我不太确定如何在一般水平上实现这一点......实现这种排序的最佳解决方案是什么?
解决方案
尝试这个:
var orderedList = documents.OrderBy(r => GetOrder(r.DocumentSection));
GetOrder()
方法是:
Public Static int GetOrder(string _arg)
{
switch (_arg)
{
case 'Section One':
return 1;
case 'Section Two':
return 2;
case 'Section Three':
return 3;
.
.
.
default:
return int.MaxValue;
}
}
推荐阅读
- vue.js - 在 vuetify 数据表中搜索没有特殊字符
- javascript - Javascript:结束时自动滚动制作反向动画
- c++ - std::initializer_list 用于 C++11 文字运算符上的参数列表
- .net-core - Microsoft.EntityFrameworkCore 异步不起作用
- reactjs - ReactJS MemoryRouter - 获取当前 URL
- java - 如何在创建时以编程方式在相对布局中设置背景图像?
- javascript - 每小时发出的 RxJS 无限流
- c# - 如何在基类中使用逆变参数?
- salesforce - 是否可以在 Salesforce 生产实例中修改触发器和类的主体?
- laravel - 在共享主机中设置 Laravel 8 和 voyager