您好我有一个问题如何分组(每个组也可以排序)和排序项目列表 - 我需要一个源列表的结果集,分组和排序 有人可以帮忙吗?
class Program
{
static void Main(string[] args)
{
List<SampleClass> source = GetItemsToProceed();
// now I want to group by GetPropNameToGroup props
// and sort each subgroup by GetPropNameToSort
// So I do sorting first
IList<SampleClass> sortedList = GetPropNamesToSort()
.Aggregate<Tuple<SortOrder, string>, IEnumerable<SampleClass>>(source, SortList)
.ToList();
// now I want to group already sorted list - HOW??
}
public IEnumerable<Tuple<SortOrder, string>> GetPropNamesToGroup()
{
return new[] { Tuple.Create(SortOrder.Ascending, "Prop1"), Tuple.Create(SortOrder.Descending, "Prop2") };
}
public IEnumerable<SampleClass> SortList(IEnumerable<SampleClass> source, Tuple<SortOrder, string> tuple)
{
var alreadyOrdered = source as IOrderedEnumerable<SampleClass>;
if (alreadyOrdered != null)
{
switch (tuple.Item1)
{
case SortOrder.Ascending:
return alreadyOrdered.ThenBy(_ => GetDataByPropName(_, tuple.Item2));
case SortOrder.Descending:
return alreadyOrdered.ThenByDescending(_ => GetDataByPropName(_, tuple.Item2));
}
}
else
{
switch (tuple.Item1)
{
case SortOrder.Ascending:
return source.OrderBy(_ => GetDataByPropName(_, tuple.Item2));
case SortOrder.Descending:
return source.OrderByDescending(_ => GetDataByPropName(_, tuple.Item2));
}
}
throw new ArgumentOutOfRangeException();
}
public static IEnumerable<Tuple<SortOrder, string>> GetPropNamesToSort()
{
return new[] { Tuple.Create(SortOrder.Ascending, "Prop3"), };
}
public object GetDataByPropName(SampleClass data, string propName)
{
switch (propName)
{
case "Prop1":
return data.Prop1;
case "Prop2":
return data.Prop2;
case "Prop3":
return data.Prop3;
case "Prop4":
return data.Prop4;
default:
throw new ArgumentOutOfRangeException();
}
}
public class SampleClass
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public string Prop3 { get; set; }
public string Prop4 { get; set; }
}
}