[英]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.