C#:排序/排序依据枚举值 [英] C#: Sort/OrderBy Enum Value
问题描述
我有我从LINQ2SQL物化一个IEnumerable。我已经过滤掉了我想要的记录,现在我要根据所选择的枚举命令他们:
I have an IEnumerable that I've materialized from Linq2Sql. I've already filtered out the records I want, now I want to order them based on a selected enum:
public enum Sort
{
Time,
Name,
Value
}
public class LinqClass
{
public DateTime Time;
public string Name;
public double Value;
}
Sort sort = Sort.Time
items.OrderBy(sort);
什么是做到这一点的最好方法是什么?我可以创建一个重载的OrderBy(排序S),这只是一个大的switch语句:
What is the best way to do this? I could create an overloaded OrderBy(Sort s) that is just a big switch statement:
switch(sort)
case Time:
return this.OrderBy(x=>x.Time);
我大概可以做一些与一本字典了。任何其他的想法,或者是有这样一个标准的模式。
I could probably do something with a dictionary too. Any other ideas, or is there a standard pattern for doing this.
推荐答案
一个switch语句可能是最好的方法,因为它。使得当一个无效的值已经通过它很容易被发现。
A switch statement is probably the best approach, as it makes it easy to spot when an invalid value has been passed.
您的可能的使用词典<排序,Func键< ; IEnumerable的< LinqClass>中的IEnumerable< LinqClass>>方式>
,但我不认为这是值得的。
You could use a Dictionary<Sort, Func<IEnumerable<LinqClass>, IEnumerable<LinqClass>>>
but I don't think it would be worth it.
这篇关于C#:排序/排序依据枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!