[英]DataTable: dynamic Group By expression by LINQ or LAMBDA
i've a DataTable in which i want to Group By for an unspecified number of fields. 我有一个DataTable,我要在其中分组一个未指定数量的字段。 This happens why user can choose fields on which he wants to group.
发生这种情况的原因是用户可以选择要分组的字段。
So, actually, i push the choise in a List. 因此,实际上,我将选择列表中的内容。 And on this choise i have to group my DataTable.
在这种选择下,我必须将我的DataTable分组。
Imagine this piece of code (VB or C# is the same): 想象一下这段代码(VB或C#相同):
public void groupFieldsFN(DataTable dt, List<string> groupFields){
var grpQuery = dt.AsEnumerable().GroupBy(r => [***groupFields***]);
}
What can i do ? 我能做什么 ? How can i express GroupBy expression in this context.
我如何在这种情况下表达GroupBy表达。
Clearly, LINQ or LAMBDA solution is the same. 显然,LINQ或LAMBDA解决方案是相同的。
Thanks in advance for the help. 先谢谢您的帮助。
_ _
SOLUTION 解
Aleks Andreev's response works! Aleks Andreev的回应有效! Thanks much.
非常感谢。
You can use custom equality comparer in GroupBy
call. 您可以在
GroupBy
调用中使用自定义相等比较器。 Define your comparer: 定义比较器:
public class CustomEqualityComparer : IEqualityComparer<DataRow>
{
private readonly List<string> groupFields;
public CustomEqualityComparer(List<string> groupFields)
{
this.groupFields = groupFields;
}
public bool Equals(DataRow x, DataRow y)
{
var xCols = groupFields.Select(f => x[f]);
var yCols = groupFields.Select(f => y[f]);
var pairs = xCols.Zip(yCols, (v1, v2) => (v1, v2));
return pairs.All(p => p.Item1.Equals(p.Item2));
}
public int GetHashCode(DataRow obj)
{
return 42; // force Equals call
}
}
And use it 并使用它
var grpQuery = dt.AsEnumerable().GroupBy(r => r, new CustomEqualityComparer(groupFields));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.