2016-08-23 35 views
-1

工作,我有這個疑問,你可以在這裏看到:明顯不適合我的查詢C#LINQ

public IQueryable<ViewReportMaterialRequestContractor> ShowReport(int MRCId) 
     { 
      var q = from m in _ctx.MaterialRequestContractorDetails 
        where m.MaterialRequestContractorId == MRCId 

        join mat in _ctx.MaterialDescriptions on m.MaterialDescriptionId equals mat.Id 
        join l in _ctx.Lines on m.LineId equals l.Id 
        join joint in _ctx.Joints on m.LineId equals joint.LineId 


        join sheet in _ctx.Sheets on joint.SheetId equals sheet.Id 
        join testjoint in _ctx.TestPackageJoints on joint.Id equals testjoint.Id 

        join testpack in _ctx.TestPackages on testjoint.TestPackageId equals testpack.Id 
        select new ViewReportMaterialRequestContractor() 
        { 
         Id = m.Id, 
         ItemCode = mat.ItemCode, 
         LineNumber = l.LineNumber, 
         Description = mat.Description, 
         Size1 = mat.Size1.ToString(), 
         Size2 = mat.Size2.ToString(), 
         DocumentNumber = l.DocumentNumber, 

        }; 
      return q; 

     } 

我打電話給我的功能在UI你可以看到:

List<ViewReportMaterialRequestContractor> lstMaterialRequestContractorDetails = _reportMaterialRequestContractorRepository.ShowReport(Id).ToList().Distinct().ToList(); 

我記錄重複4次,我有4個記錄重複4次,所以我有16個記錄,所以我必須使用不同的刪除重複的記錄。

但結果再次顯示16條記錄。爲什麼?

+1

如何前'Distinct' –

+0

刪除'ToList' @IvanStoev讓我查 –

+0

@IvanStoev感謝它的工作原理,但是爲什麼呢?因爲我覺得不同的條款應被執行,因爲,我有之前不同, –

回答

1

當你做.ShowReport(Id).ToList().Distinct().ToList()被稱爲Distinct()Enumerable.Distinct<TSource>(this IEnumerable<TSource> source),將會產生一個從第一.ToList()一個內存中的集合,然後用平等的規則做了不同的.NET爲ViewReportMaterialRequestContractor類(這將是在默認情況下,通過比較如果你還沒有覆蓋.Equals(object).GetHashCode()

當你做.ShowReport(Id).Distinct().ToList()被稱爲Distinct()Queryable.Distinct<TSource>(this IQueryable<TSource> source),這個轉換的不同之處在一個SQL查詢電話,並使用平等執行它的服務器上,對象引用,而不是值SQL服務器中的規則(將按每個返回列的值進行比較)

+0

但不要匿名類型實現自動值相等比較所有領域?我的印象是這裏使用了匿名類型的覆蓋「Equals」。 – InBetween

+0

@InBetween OP沒有創建一個annonamous類型,OP正在處理一個'ViewReportMaterialRequestContractor',讓OP使用一個匿名類型,我認爲OP會得到相同的行爲。爲了得到與真實類型相同的行爲,OP將需要覆蓋'ViewReportMaterialRequestContractor'類的'.Equals'和'.GetHashCode',以便在它檢查相等時比較類中的所有字段。 –

+0

Duh,當你閱讀代碼太快時會發生這種情況。我認爲這是一種匿名類型,而不是現有類型。現在清楚,謝謝。 – InBetween