2016-06-24 68 views
1

我不是linq最棒的,但它是選擇的語言。我正在嘗試使用sql來編寫查詢。標準scenerio我有一張發票,發票上有發票細節。當加入表格時,具有多個細節的發票將重複。在標準的SQL中,我可以使用distinct或group by。我試圖用linq跟蹤,但得到錯誤,或者它只是不過濾掉它們。使用linq查詢刪除重複的行

這裏是我的查詢

var result = (from invoice in invoices 
     join invoiceItem in invItems on invoice.Id equals invoiceItem.InvoiceId 
     orderby invoice.InvoiceNo 
     select new InvoiceReceiveShipmentVM 
     { 
      dtInvoiced = invoice.dtInvoiced, 
      InvoiceNumber = invoice.InvoiceNo, 
      InvoiceType = invoice.InvoiceType, 
      InvoiceStatus = invoice.InvoiceStatus, 
      Lines = invoiceItem.Line, 
      Total = invoice.Total, 
      Carrier = invoice.Carrier, 
     }); 
return result.Distinct(); 

我也試過:

  var myList = result.GroupBy(x => x.InvoiceNumber) 
          .Select(g => g.First()).ToList(); 
     return myList.Skip(fetch.Skip).Take(fetch.Take).AsQueryable(); 
+3

你或許應該描述你希望過濾掉。例如也許顯示你期望得到的結果,以及這個查詢是什麼(錯誤地?)給你。 – failedprogramming

回答

0

使用不同,請重載Equals和GetHashCode在InvoiceReceiveShipmentVM

public class InvoiceReceiveShipmentVM 
{ 
    public override bool Equals(object obj) 
    { 
     if (obj is InvoiceReceiveShipmentVM == false) return false; 

     var invoice = (InvoiceReceiveShipmentVM)obj; 
     return invoice.InvoiceNumber == InvoiceNumber 
      && invoice.InvoiceType == InvoiceType 
      && invoice.InvoiceStatus == InvoiceStatus 
      && invoice.Lines == Lines 
      && invoice.Total == Total 
      && invoice.Carrier == Carrier; 
    } 
    public override int GetHashCode() 
    { 
     return InvoiceNumber.GetHashCode() 
      ^InvoiceType.GetHashCode() 
      ^InvoiceStatus.GetHashCode() 
      ^Lines.GetHashCode() 
      ^Total.GetHashCode() 
      ^Carrier.GetHashCode(); 
    } 
}