gpt4 book ai didi

c# - LINQ 和引用列表问题

转载 作者:太空狗 更新时间:2023-10-30 01:24:12 25 4
gpt4 key购买 nike

我有以下 LINQ 代码

var q = (from web in DataContext.Webs select web);
List<int?> k1 = new List<int?>() { 1, 2 };
List<int?> k2=new List<int?>() { 16, 17 };
q = q.Where(web => DataContext.WebTechMaps.Any(t => t.WebsiteId == web.WebsiteId && k1.Contains(t.TechId)));
System.Diagnostics.Debug.WriteLine(q.Count());
k1 = k2;
q = q.Where(web => DataContext.WebTechMaps.Any(t => t.WebsiteId == web.WebsiteId && k1.Contains(t.TechId)));
System.Diagnostics.Debug.WriteLine(q.Count());

这是它生成的查询。

第一次执行计数。

SELECT COUNT(*) AS [value]
FROM [dbo].[Web] AS [t0]
WHERE EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[WebTechMap] AS [t1]
WHERE ([t1].[WebsiteId] = ([t0].[WebsiteId])) AND ([t1].[TechId] IN (@p0, @p1))
)
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [2]

第二次执行计数函数

SELECT COUNT(*) AS [value]
FROM [dbo].[Web] AS [t0]
WHERE (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[WebTechMap] AS [t1]
WHERE ([t1].[WebsiteId] = ([t0].[WebsiteId])) AND ([t1].[TechId] IN (@p0, @p1))
)) AND (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[WebTechMap] AS [t2]
WHERE ([t2].[WebsiteId] = ([t0].[WebsiteId])) AND ([t2].[TechId] IN (@p2, @p3))
))
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [17]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [17]

请查看传递给查询的参数。

似乎它对两个表达式都使用了新的引用对象。

@p0 和@p1 以某种方式更改了它们的旧值。我知道问题出在 Linq 中,它使用了新的引用对象。

-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [2]



-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [17]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [17]

有人可以解释如何使用相同名称的 List 对象,但使用正确的 List 来保持查询

期望的输出是

-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [2]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [17]

提前致谢

最佳答案

您的第一个查询表达式使用 k1。它使用变量 kl,这就是捕获的内容。当您更改 k1 的值时,这实际上改变了查询的含义。如果不想改变查询的意义,就不要改变捕获的变量!只需在第二个过滤器中使用 k2:

var q = (from web in DataContext.Webs select web);
List<int?> k1 = new List<int?>() { 1, 2 };
List<int?> k2=new List<int?>() { 16, 17 };
q = q.Where(web => DataContext.WebTechMaps
.Any(t => t.WebsiteId == web.WebsiteId &&
k1.Contains(t.TechId)));
System.Diagnostics.Debug.WriteLine(q.Count());
q = q.Where(web => DataContext.WebTechMaps
.Any(t => t.WebsiteId == web.WebsiteId &&
k2.Contains(t.TechId)));
System.Diagnostics.Debug.WriteLine(q.Count());

关于c# - LINQ 和引用列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10046991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com