我不是linq的最佳人选,但却是首选语言。我正在尝试使用sql编写查询。标准场景我有发票,发票上有发票详细信息。当将表格连接在一起时,具有多个细节的发票将重复进行。在标准的SQL中我可以使用distinct或group by。我试图用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();
答案 0 :(得分:0)
使用distinct,请覆盖InvoiceReceiveShipmentVM中的Equals和GetHashCode
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();
}
}