[英]How to query two tables for matching values with linq and C#?
我是C#和Linq的新手,在查詢兩個表中的匹配值時遇到了一些麻煩。
在我作為實習生的地方,我們使用工作單元存儲庫模式。 例如,要查詢sql表,我將使用以下linq表達式: _entities.Atable.Where(x => x.Col1 == col1 && x.Col2 == col2)
。 _entities
變量表示數據庫模型中所有表的接口。
假設我有兩個表Table1
和Table2
。 這是每個表的列:
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.Col1
和Table2.Col2
與List1.Col1
和List1.Col2
匹配的任何記錄。 這些結果也可以存儲在List2
。
例如, List2 = _entities.Table2.Where(x => x.Col1 == List1.Col1 && x.Col2 == List1.Col2).ToList()
List3
,其中包含Table1
中與Table2
中的項目不匹配的任何項目 最后,我想列出由Col1
和Col2
匹配Table1的Table2
項列表。 而剩余的清單Table1
項不存在其在沒有匹配Table2
。
通常,我停留在第三個要點上,但是我願意接受任何建議和改進。
最后,我不知道是否可行,我想將兩個列表合並為一個。 由於它們是不同的類型,所以我不確定這將如何工作。
我希望所有這些都是有道理的。 我一直在想辦法,但我仍然對如何創建查詢感到困惑。 我也玩過Except()
和Intersect()
但是運氣不高。
任何幫助將不勝感激。
我通常發現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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.