Skip to main content
 首页 » 编程设计

c#之我如何处理此 linq 查询并将其与 if 语句中的 int 进行比较

2024年02月06日13落叶无声

我有以下代码:

 int selectedcourseId = Convert.ToInt32(c1.Text); 
 var cid = (from g in re.Sections where g.CourseID == selectedcourseId select g.CourseID);  
 
int selectedinstructorid = Convert.ToInt32(c2.Text); 
var iid = (from u in re.Sections where u.InstructorID == selectedinstructorid select u.InstructorID); 

我想在 if 语句中比较两个 (selectedcourseId) 与 (cid) 和 (selectedinstructorid) 与 (iid),例如:

  if (selectedcourseId = cid && selectedinstructorid = iid) 
           { 
                MessageBox.Show("it already exists"); 
           } 

我已经尝试了很多没有用的东西,因为我的知识有限。 非常感谢您的任何评论或回答

请您参考如下方法:

您可以将您的代码更改为:(但检查此内容对您的情况毫无意义)

 if (selectedcourseId == cid.First() && selectedinstructorid == iid.First()) 

首先要在 if 语句中检查相等性,您必须使用 == , 不是 = .第二个是 IQueryable<T>允许您针对特定数据源执行查询,但它使用延迟执行。为了在您的情况下执行它,您可以使用 First() .

但是,我建议您只是在学习如何使用 LINQ,因此您已经编写了这段代码。

我不知道你想要达到什么目的。但是,如果您想搜索是否有任何带有该 ID 的结果,则必须使用 Any() :

var result1 = from g in re.Sections where g.CourseID == selectedcourseId select g.CourseID; 
var result2 = from u in re.Sections where u.InstructorID == selectedinstructorid select u.InstructorID; 
 
if(result1.Any() && result2.Any()) { ... } 

或者,如果你想查找是否有指定了 CourseID 的行和 InstructorID , 然后你可以调用一个 Any() :

 if(re.Sections.Any(x => x.CourseID == selectedcourseId && x.InstructorID == selectedinstructorid))   
 { ... }