【问题标题】:Check if a value is in a collection with LINQ使用 LINQ 检查值是否在集合中
【发布时间】:2010-11-14 00:16:06
【问题描述】:

我有一个“Employee”类,它有一个“TypeOfWork”的 IList。

public class Employee
{
    public virtual IList<TypeOfWork> TypeOfWorks { get; set; }
}

public class TypeOfWork
{
    public virtual Customer Customer { get; set; }

    public virtual Guid Id { get; set; }
    public virtual string Name{ get; set; }
    public virtual bool IsActive{ get; set; }
}

在保存之前,我想知道“typeofwid”(一个 Guid)是否已经在“TypeOfWorks”集合中。

我试过这个:

var res =  from p in employee.TypeOfWorks 
           where p.Id == new Guid("11111111-1111-1111-1111-111111111111") 
           select p ;

并尝试过:

bool res = employee.TypeOfWorks.Where(f => f.Id == new Guid("11111111-1111-1111-1111-111111111111")).Count() != 0;

在 Visual Studio 的“即时窗口”中,但我收到错误:表达式不能包含查询表达式在这两种情况下

你有什么想法吗?

谢谢,

【问题讨论】:

    标签: c# linq collections lambda


    【解决方案1】:

    正是错误所说的。您不能在即时窗口中使用 LINQ 查询,因为它们需要编译 lambda 函数。尝试实际代码中的第一行,它可以在其中编译。 :)

    此外,要在一行中完成所有操作,您可以使用 LINQ“Any”运算符,如下所示:

    if( ! employee.TypeOfWorks.Any(tow => tow.Id == theNewGUID) )
        //save logic for TypeOfWork containing theNewGUID
    

    【讨论】:

      【解决方案2】:

      怎么样

      Guid guid = Guid.NewGuid("11111111-1111-1111-1111-111111111111");
      var res =  from p in employee.TypeOfWorks  
                 where p.Id == guid  
                 select p ; 
      
      The problem is constructing the guid - otherwise the linq queries should work
      

      【讨论】:

        【解决方案3】:

        实际上,我认为其中任何一个都有效。请记住,Visual Studio 也无法在监视窗口中处理 Linq 查询,因此我怀疑您看到的错误更多的是 Visual Studio 问题,而不是代码无法正常工作。

        【讨论】:

          【解决方案4】:

          尝试使用此代码获取未初始化的 typeofwork 的计数。

          if(employee.TypeOfWorks
              .Count(f => f.Id != new Guid("11111111-1111-1111-1111-111111111111")) != 0)
          {
              //do something
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-02-17
            • 1970-01-01
            • 2017-06-04
            • 2014-03-24
            • 2019-06-18
            • 1970-01-01
            • 2013-04-26
            • 1970-01-01
            相关资源
            最近更新 更多