2014-06-06 55 views
1

我對C#和Linq很新,我在查詢兩個表的匹配值時遇到了一些麻煩。如何查詢兩個表與linq和C#匹配的值?

作爲實習生,我們使用工作單元庫模式。例如,要查詢一個sql表,我會使用這個linq表達式:_entities.Atable.Where(x => x.Col1 == col1 && x.Col2 == col2)。變量_entities表示數據庫模型中所有表的接口。

假設我有兩個表Table1Table2。下面是每個表中的列:

Table1: Col1, Col2, colA, ColB 
Table2: Col1, col2, ColC, ColD 

這是我想做些什麼:通過匹配兩個變量,col1和col2上,與col1和col2的

  • 查詢Table1

    例如,List1 = _entities.Table1.Where(x => x.Col1 == col1 && x.Col2 == col2).ToList()

  • 然後,查詢Table2任何記錄,其中Table2.Col1Table2.Col2匹配List1.Col1List1.Col2。這些結果也可以存儲在列表中,List2

    例如,List2 = _entities.Table2.Where(x => x.Col1 == List1.Col1 && x.Col2 == List1.Col2).ToList()

  • 然後,使第三列表,List3,包含從Table1任何項目未從Table2

匹配項最後,我想有一個列表Table2與Table1匹配的項目Col1Col2。以及Table2中沒有匹配的剩餘物品Table1的清單。

大多數情況下,我被困在第三個要點上,但我願意接受任何建議和改進。

最後,我不知道這是否可能,我想將兩個列表合併爲一個。由於它們是不同的類型,我不確定這將如何工作。

我希望這一切都有道理。我一直試圖繞過它一段時間,但我仍然難以理解如何創建查詢。我也玩過Except()Intersect(),但沒有太多的運氣。

任何幫助將不勝感激。

+0

嘗試'差異()'而不是'除()'? – Monkpit

+0

好的,我會開始研究它。謝謝。 – navig8tr

+0

你想要做一個左內連接嗎? –

回答

2

我通常發現Any是匹配來自不同類型的多個值的最清晰的方法。

class Type1 
{ 
    public int Key1 { get; set; } 
    public int Key2 { get; set; } 
    public string Type1Prop { get; set; } 
    public Type1(int key1, int key2, string prop) 
    { 
     Key1 = key1; 
     Key2 = key2; 
     Type1Prop = prop; 
    } 
} 

class Type2 
{ 
    public int Key1 { get; set; } 
    public int Key2 { get; set; } 
    public string Type2Prop { get; set; } 
    public Type2(int key1, int key2, string prop) 
    { 
     Key1 = key1; 
     Key2 = key2; 
     Type2Prop = prop; 
    } 
} 

public void Main() 
{ 
    var list1 = new List<Type1> 
    { 
     new Type1(1,1,"Value"), new Type1(1,2,"Value"), new Type1(2,1,"Value"), new Type1(2,2,"Value") 
    }; 
    var list2 = new List<Type2> 
    { 
     new Type2(1,1,"Value"), new Type2(2,1,"Value"), new Type2(3,1,"Value") 
    }; 
    var in1ButNot2 = list1.Where(item => !list2.Any(item2 => item2.Key1 == item.Key1 && item2.Key2 == item.Key2)).ToList(); 
    var in2ButNot1 = list2.Where(item => !list1.Any(item2 => item2.Key1 == item.Key1 && item2.Key2 == item.Key2)).ToList(); 
    var in1And2 = list2.Where(item => list1.Any(item2 => item2.Key1 == item.Key1 && item2.Key2 == item.Key2)).ToList(); 
    in1ButNot2.ForEach(item => Console.WriteLine("in1ButNot2 - Key1={0},Key2={1}", item.Key1, item.Key2)); 
    in2ButNot1.ForEach(item => Console.WriteLine("in2ButNot1 - Key1={0},Key2={1}", item.Key1, item.Key2)); 
    in1And2.ForEach(item => Console.WriteLine("in1And2 - Key1={0},Key2={1}", item.Key1, item.Key2)); 
} 

這樣就結束了輸出以下內容並向您顯示所有可以交叉數據的方式。如果您只需要密鑰,然後您可以創建一個通用類型並將其轉換爲一個組合列表,那麼組合列表就是您必須弄清楚自己的問題。

in1ButNot2 - Key1=1,Key2=2 
in1ButNot2 - Key1=2,Key2=2 
in2ButNot1 - Key1=3,Key2=1 
in1And2 - Key1=1,Key2=1 
in1And2 - Key1=2,Key2=1 
+0

很好的答案!正是我所希望的。非常感謝! – navig8tr