DataTable: dynamic Group By expression by LINQ or

2020-05-09 23:14发布

问题:

i've a DataTable in which i want to Group By for an unspecified number of fields. 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.

Imagine this piece of code (VB or C# is the same):

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.

Clearly, LINQ or LAMBDA solution is the same.

Thanks in advance for the help.

_

SOLUTION

Aleks Andreev's response works! Thanks much.

回答1:

You can use custom equality comparer in GroupBy call. 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));