C# LINQ返回不匹配项查询
我有两个不同类型的数组,一个来自文件,另一个来自SQL数据库——LINQ到SQL。我正试图根据通过文件接收的项目从数据库中删除不匹配的项目。(我提到这一点是为了防止有一种更有效的方法来实现我的目标) 我已经起草了几个匿名数组来展示我正在尝试做什么:C# LINQ返回不匹配项查询,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,我有两个不同类型的数组,一个来自文件,另一个来自SQL数据库——LINQ到SQL。我正试图根据通过文件接收的项目从数据库中删除不匹配的项目。(我提到这一点是为了防止有一种更有效的方法来实现我的目标) 我已经起草了几个匿名数组来展示我正在尝试做什么: var a = new[] { new { code = "A", subid = 1, test = "dunno" }, new { code = "A", subid = 2, test = "dunno" }, new { code
var a = new[] {
new { code = "A", subid = 1, test = "dunno" }, new { code = "A", subid = 2, test = "dunno" }, new { code = "A", subid = 3, test = "dunno" },
new { code = "B", subid = 1, test = "dunno" }, new { code = "B", subid = 2, test = "dunno" }, new { code = "B", subid = 3, test = "dunno" }
};
var c = new[] {
new { code = "A", subid = 1 }, new { code = "A", subid = 2 },
new { code = "B", subid = 1 }, new { code = "B", subid = 2 }
};
我需要它返回不匹配的项,例如new{code=“A”,subid=3}
和new{code=“B”,subid=3}
var b = (from items in a
where c.Any(d => d.code == items.code && d.subid != items.subid)
select items);
及
var b = (from items in a
where c.Where(d=> d.code == items.code).Any(d => d.subid != items.subid)
select items);
我试过了,但他们似乎把所有的东西都退回了。我如何做到这一点?使用
全样本:
var a = new[] {
new { code = "A", subid = 1 },
new { code = "A", subid = 2 },
new { code = "A", subid = 3 },
new { code = "B", subid = 1 },
new { code = "B", subid = 2 },
new { code = "B", subid = 3 }
};
var c = new[] {
new { code = "A", subid = 1 },
new { code = "A", subid = 2 },
new { code = "B", subid = 1 },
new { code = "B", subid = 2 }
};
foreach(vat item in a.Except(c))
Console.WriteLine(item);
// { code = A, subid = 3 }
// { code = B, subid = 3 }
更新(如果您有不同的类型,并且希望查找某些字段集的匹配项,则使用序列联接,并从与c
中的某些项匹配的a
中删除所有项:
var matchingItems = from aa in a
join cc in c
on new { aa.code, aa.subid } equals // properties subset
new { cc.code, cc.subid } // same subset
select aa; // select inner item from join
var nonMatchingItems = a.Except(matchingItems);
我的应用程序中的匿名数组没有匹配的属性。这仍然有效吗?好吧。你需要为匿名对象实现相等运算符。@lazyberezovsky不,它们只是GetHashCode(),如果它们有特殊要求,这将使OP出错。只是一张便条@Smithy除了连接外,您还可以处理不同类型的连接,请参见update@lazyberezovsky…将数组转换为匹配的匿名类型,然后执行.Except()-我只是在代码中尝试了这一点。非常感谢:)
var matchingItems = from aa in a
join cc in c
on new { aa.code, aa.subid } equals // properties subset
new { cc.code, cc.subid } // same subset
select aa; // select inner item from join
var nonMatchingItems = a.Except(matchingItems);