很久以前,我为此目的创建了一个扩展方法。我刚刚再次遇到了对它的需求:
public static IOrderedEnumerable<TSource> OrderByWeight<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, int> weighting) where TKey : IComparable
{
Dictionary<TSource, int> order = new Dictionary<TSource, int>();
foreach (TSource item in source)
{
if (!order.ContainsKey(item)) order.Add(item, weighting(keySelector(item)));
}
return source.OrderBy(s => order[s]);
}
你可以像这样使用它:
var data = dt.Select(g => new
{
Season = g.season,
AverageTemp = g.temp
}).OrderByWeight(a => a.Season, x =>
{
if (x == "WINTER") return 1;
if (x == "SPRING") return 2;
if (x == "SUMMER") return 3;
if (x == "AUTUMN") return 4;
return 99;
});
来源:来自我的旧博客