我有一个 telerik 网格,我将对象列表数据绑定(bind)到页面上。用户可以在查看数据时根据自己的喜好对列进行分组。我正在编写一个函数以将此数据导出到 excel 文档中,并希望保留用户在页面上的分组。我能够获取用户分组所依据的对象属性的字符串名称。
我坚持的是如何在运行时进行分组。有很多这样的例子:Group by with multiple columns using lambda描述如何在您提前知道的情况下在编译时按多个属性分组。但是,直到在运行时我才知道要分组的内容。
关于如何在运行时进行分组有什么建议吗?
最佳答案
您可能正在寻找类似 this SO question 的答案,特别是:
var myData = gridData.AsEnumerable()
.GroupBy(r => r, new MyDataComparer(keys))
.ToList();
internal class MyDataComparer : IEqualityComparer<MyDataType>
{
private readonly string[] _keys;
public MyDataComparer(string[] keys)
{
_keys = keys; // keep the keys to compare by.
}
public bool Equals(MyDataType x, MyDataType y)
{
// a simple implementation that checks if all the required fields
// match. This might need more work.
bool areEqual = true;
foreach (var key in _keys)
{
areEqual &= (x[key].Equals(y[key]));
}
return areEqual;
}
public int GetHashCode(DataRow obj)
{
// Add implementation here to create an aggregate hashcode.
}
}
关于c# - 按运行时已知的多个键分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26889348/