首页 > 解决方案 > 基于字符串属性值的 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 来获得它,但这就是困难所在,我不太确定如何在一般水平上实现这一点......实现这种排序的最佳解决方案是什么?

标签: c#.netalgorithmlinq

解决方案


尝试这个:

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;
    }
}

推荐阅读