检查一个值是否在与LINQ的集合中

检查一个值是否在与LINQ的集合中

问题描述:

我有一个“Employee”类,它有一个IList类型为“TypeOfWork”的IList <>。检查一个值是否在与LINQ的集合中

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中的 “立即窗口”,但我收到的错误:在这两个表达式不能包含查询表达式案例

您有想法吗?

谢谢,

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

此外,为了得到这一切在一行完成后,你可以使用LINQ“任何”运算符,就像这样:

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

我觉得无论这些工作,其实。请记住,Visual Studio无法在监视窗口中处理Linq查询,所以我怀疑你看到的错误更多的是Visual Studio问题,而不是代码不工作。

试试这个代码来获得未初始化的typeofwork的计数。

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

怎么样

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