Grouping in Linq ( on multiple fields)

后端 未结 1 997
不思量自难忘°
不思量自难忘° 2021-01-22 09:51

I am grouping some data using linq as following :

var groupedData = from row in salesTable.AsEnumerable()                   
group row by   
row.Field

        
相关标签:
1条回答
  • 2021-01-22 10:22

    Use an anonymously typed object for the grouping.

     var groupedData = from row in salesTable.AsEnumerable()                   
                       group row by new
                       {
                            InvoiceNum = row.Field<string>("InvoiceNum"),
                            InvoiceLineNum = row.Field<string>("InvoiceLineNum")
                       }
                       into grp
                       select grp;
    

    or using a named class

    public class InvoiceGrouping : IEquatable<InvoiceGrouping>
    {
         public string InvoiceNum { get; set; }
         public string InvoiceLineNum { get; set; }
    
         public bool Equals( InvoiceGrouping other )
         {
             return other != null 
                    && this.InvoiceNum == other.InvoiceNum
                    && this.InvoiceLineNum == other.InvoiceLineNum;
         }
    
         public override bool Equals( object other )
         {
             return Equals( other as InvoiceGrouping );
         }
    
         public override int GetHashCode()
         {
             unchecked
             {
                int hash = 17;
                hash *= (this.InvoiceNum != null ? 23 + this.InvoiceNum.GetHashCode() : 1);
                hash *= (this.InvoiceLineNum != null ? 23 + this.InvoiceLineNum.GetHashCode() : 1 );
                return hash;
             }
         }
     }
    
     var groupedData = from row in salesTable.AsEnumerable()                   
                       group row by new InvoiceGrouping
                       {
                            InvoiceNum = row.Field<string>("InvoiceNum"),
                            InvoiceLineNum = row.Field<string>("InvoiceLineNum")
                       }
                       into grp
                       select grp;
    
    0 讨论(0)
提交回复
热议问题