DataTable: dynamic Group By expression by LINQ or LAMBDA

前端 未结 1 1278
南笙
南笙 2021-01-29 07:13

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 pu

相关标签:
1条回答
  • 2021-01-29 07:42

    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));
    
    0 讨论(0)
提交回复
热议问题