68 lines
2.0 KiB
C#
68 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics.Contracts;
|
|
using System.Linq;
|
|
|
|
namespace APT.Infrastructure.Core
|
|
{
|
|
/// <summary>
|
|
/// Linq 拓展方法类
|
|
/// </summary>
|
|
public static class LinqExtensions
|
|
{
|
|
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
|
|
{
|
|
Contract.Requires(action != null);
|
|
foreach (var element in source)
|
|
action(element);
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
}
|