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

标签 c# linq

我有以下代码:

 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))  
 { ... }

关于c# - 我如何处理此 linq 查询并将其与 if 语句中的 int 进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28941507/

相关文章:

c# - 多语言应用程序工具包 .xlf 文件在构建期间未更新

c# - 如何使用 protobuf-net 代理序列化继承链中的类型?

c# - 带有 C# 驱动程序 2.0 : How to get the result from InsertOneAsync 的 MongoDB(服务器 v 2.6.7)

c# - 将 Array 的特定项目放在末尾

C# Linq All & Any 在空白数组上的工作方式不同

c# - Linq DataContext 最佳实践

c# - 如何基于多个xml属性存储和查找数据?

c# - 如何从字典中为某些键选择所有键值对

c# - 使用 iTextSharp 填写 PDF 表格并通过电子邮件发送填写好的表格

c# - 为什么 BluetoothLEDevice.GattServices 为空