在Linq分组(在多个领域)

Gai*_*ter 2 .net c# linq

我正在使用linq对一些数据进行分组,如下所示:

var groupedData = from row in salesTable.AsEnumerable()                   
group row by   
row.Field<string>("InvoiceNum") into grp
select grp;
Run Code Online (Sandbox Code Playgroud)

我想重新集结groupedData使用像某些领域row.Field("InvoiceNum"),row.Field("InvoiceLineNum") ,我不知道如何LINQ的分组与多个领域的工作?

tva*_*son 9

使用匿名类型对象进行分组.

 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;
Run Code Online (Sandbox Code Playgroud)

或使用命名类

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;
Run Code Online (Sandbox Code Playgroud)