1.首先写一个linq扩展类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace aaa.utils
{
static class LinqExt
{
public class DGroupBy<T> : IGrouping<object[], T>
{
private List<T> _innerlist = new List<T>();
private object[] _key;
public DGroupBy(object[] key) { _key = key; }
public object[] Key
{
get { return _key; }
}
public void Add(T value)
{
_innerlist.Add(value);
}
public IEnumerator<T> GetEnumerator()
{
return this._innerlist.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this._innerlist.GetEnumerator();
}
}
public static IEnumerable<IGrouping<object[], T>> DynamicGroupBy<T>(this IEnumerable<T> data, string[] keys)
{
List<DGroupBy<T>> list = new List<DGroupBy<T>>();
foreach (var item in data.Select(x => new
{
k = keys.Select(y => x.GetType().GetProperty(y).GetValue(x, null)).ToArray(),
v = x
}))
{
DGroupBy<T> existing = list.SingleOrDefault(x => x.Key.Zip(item.k, (a, b) => a.Equals(b)).All(y => y));
if (existing == null)
{
existing = new DGroupBy<T>(item.k);
list.Add(existing);
}
existing.Add(item.v);
}
return list;
}
}
}
2.定义一个员工类
public class Employee
{
public int ID {get;set;}
public string No {get;set;}
public string Name {get;set;}
public int Age {get;set;}
public string City{get;set;}
public string Address {get;set;}
}
3.创建员工信息
List<Employee> employees = new List<Employee>()
{
new Employee() { ID = 1, Age = 20, City = "BJ", Name = "A" },
new Employee() { ID = 2, Age = 20, City = "BJ", Name = "B" },
new Employee() { ID = 3, Age = 20, City = "BJ", Name = "C" },
new Employee() { ID = 4, Age = 20, City = "SH", Name = "D" },
new Employee() { ID = 5, Age = 30, City = "SH", Name = "E" },
new Employee() { ID = 6, Age = 30, City = "SH", Name = "F" },
new Employee() { ID = 7, Age = 30, City = "CD", Name = "G" },
new Employee() { ID = 8, Age = 30, City = "CD", Name = "H" },
new Employee() { ID = 9, Age = 30, City = "HK", Name = "I" },
new Employee() { ID = 10, Age = 30, City = "HK", Name = "J" },
};
4 使用实例
var query = employees.DynamicGroupBy(new string[] { "City" });
foreach (var item in query)
{
Debug.WriteLine(item.Count()); //记录数
Debug.WriteLine("Key: {0}"+string.Join(",", item.Key.Select(x => x.ToString())));
foreach (var item1 in item)
{
var propNameVal = item1.GetType().GetProperty("ID").GetValue(item1, null); // 通过反射 获取属性值
var propNameVal1 = item1.GetType().GetProperty("City").GetValue(item1, null);
Debug.WriteLine($" Name {propNameVal} {propNameVal1}");
}
}