c# – 除列外的Linq组
发布时间:2020-12-15 21:05:17 所属栏目:百科 来源:网络整理
导读:我有一个具有大量属性的类,我需要按几乎所有列进行分组. 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 {
我有一个具有大量属性的类,我需要按几乎所有列进行分组.
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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |