我有一个具有大量属性的类,我需要按几乎所有列进行分组.
class Sample { public string S1 { get; set; } public string S2 { get; set; } public string S3 { get; set; } public string S4 { get; set; } // ... all the way to this: public string S99 { get; set; } public decimal? N1 { get; set; } public decimal? N2 { get; set; } public decimal? N3 { get; set; } public decimal? N4 { get; set; } // ... all the way to this: public decimal? N99 { get; set; } }
有时我需要按除除一个或两个十进制列之外的所有列进行分组,并根据此返回一些结果(即具有所有字段的对象,但将一些十进制值作为总和或最大值).
是否有任何扩展方法可以让我做这样的事情:
sampleCollection.GroupByExcept(x => x.N2,x => x.N5).Select(....);
而不是指定对象中的所有列?
解决方法
借用这个答案
here:
创建一个EqualityComparer类
public class EqualityComparer<T> : IEqualityComparer<T> { public bool Equals(T x,T y) { IDictionary<string,object> xP = x as IDictionary<string,object>; IDictionary<string,object> yP = y as IDictionary<string,object>; if (xP.Count != yP.Count) return false; if (xP.Keys.Except(yP.Keys).Any()) return false; if (yP.Keys.Except(xP.Keys).Any()) return false; foreach (var pair in xP) if (pair.Value.Equals( yP[pair.Key])==false) return false; return true; } public int GetHashCode(T obj) { return obj.ToString().GetHashCode(); } }
然后创建GroupContent方法:
private void GroupContent<T>(List<T> dataList,string[] columns,string[] columnsToExclude) { string[] columnsToGroup = columns.Except(columnsToExclude).ToArray(); EqualityComparer<IDictionary<string,object>> equalityComparer = new EqualityComparer<IDictionary<string,object>>(); var groupedList = dataList.GroupBy(x => { var groupByColumns = new System.Dynamic.ExpandoObject(); ((IDictionary<string,object>)groupByColumns).Clear(); foreach (string column in columnsToGroup) ((IDictionary<string,object>)groupByColumns).Add(column,GetPropertyValue(x,column)); return groupByColumns; },equalityComparer); foreach (var item in groupedList) { Console.WriteLine("Group : " + string.Join(",",item.Key)); foreach (object obj in item) Console.WriteLine("Item : " + obj); Console.WriteLine(); } } private static object GetPropertyValue(object obj,string propertyName) { return obj.GetType().GetProperty(propertyName).GetValue(obj,null); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。