基于字符串属性值的列表上的Custom OrderBy [英] Custom OrderBy on a List based on a string property value
本文介绍了基于字符串属性值的列表上的Custom OrderBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
public class Document
{
public string DocumentSection { get; set; }
public string DocumentName { get; set; }
}
,我想根据DocumentSection属性订购以下列表:
and I would like to order the following list based on the DocumentSection property:
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来实现这一目标,但这就是困难所在,我不太确定如何在总体上实现这一目标……什么是实现这一目标的最佳解决方案?订购吗?
In theory I know that I should implement IComparer to obtain that, but this is where the difficulty comes in, I am not very sure how can I achieve that on a general level ... what is the best solution to achieve this ordering ?
推荐答案
尝试一下:
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;
}
}
这篇关于基于字符串属性值的列表上的Custom OrderBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文