Check if a value is in a collection with LINQ

16,061

Solution 1

Just what the error says. You can't use LINQ queries in the Immediate Window because they require compilation of lambda functions. Try the first line in your actual code, where it can be compiled. :)

Also, to get this all done in one line, you can use the LINQ "Any" operator, like so:

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

Solution 2

how about

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
Share:
16,061
Kris-I
Author by

Kris-I

.NET Consulting

Updated on June 14, 2022

Comments

  • Kris-I
    Kris-I almost 2 years

    I have a class "Employee", this has an IList<> of "TypeOfWork".

    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; }
    }
    

    before saving, I'd lile to know if "typeofwid" (a Guid) is already in the "TypeOfWorks" collection.

    I tried this :

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

    and tried this :

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

    in the "Immediate Window" of Visual Studio but I receive the error : Expression cannot contain query expressions in both case

    Do you have an idea ?

    Thanks,