gpt4 book ai didi

c# - Linq 分组除列

转载 作者:行者123 更新时间:2023-12-03 17:38:34 24 4
gpt4 key购买 nike

我有一个包含大量属性的类,我需要按几乎所有列对其进行分组。

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:

创建类(class) 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);
}

关于c# - Linq 分组除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42116767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com