2014-04-03 77 views
2
public class ConsumableThreshold 
{ 
    public int ThresholdType { get; set; } 
    public int ManufacturerID { get; set; } 
    public int ModelID { get; set; } 
    public int ConsumableVariantID { get; set; } 
} 

我試圖檢查共享屬性的兩個對象列表。 根據以前的比賽結果,我需要檢查各種其他屬性。在多個條件下比較列表

例如,如果ThresholdType匹配,然後我需要檢查第二個屬性,如果匹配,我需要檢查ModelID。

我有這個查詢,它有效地做我想要的,但有問題,主要是進一步下來我鑽更多的可讀性將減少。

var query= existingThresholds.Where(
    e => defaultThresholds.Any(
     d => d.ThresholdType == e.ThresholdType)).Where(
      e => defaultThresholds.Any(
       d => d.ManufacturerID == e.ManufacturerID)).ToList(); 

我想做到這一點使用join,但它不支持&&操作。

var query2 = from e in existingThresholds 
      join d in defaultThresholdson 
      e.ThresholdType equals d.ThresholdType && 
      e.ManufacturerID equals d.ManufacturerID 
      select e; 

有沒有一種方法來寫這個查詢,而無需鏈接.Where()條件?

回答

6

當然 - 你只是想加入一個複合鍵,這通常是一個匿名類型來實現:

var query2 = from e in existingThresholds 
      join d in defaultThresholdson 
      on new { e.ThresholdType, e.ManufacturerID } equals 
       new { d.ThresholdType, d.ManufacturerID } 
      select e; 

(這是有點奇怪忽視的加入以後一半,無可否認。 ..)

3

有沒有一種方法來寫這個查詢沒有鏈接.Where()條件?

是,使用匿名類型,它有一個內置的平等檢查,通過名稱的所有屬性的值進行比較:

var query2 = from e in existingThresholds 
      join d in defaultThresholds 
      on  new { e.ThresholdType , e.ManufacturerID } 
       equals new { d.ThresholdType , d.ManufacturerID } 
      select e;