Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value is in a collection with LINQ

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,

like image 596
Kris-I Avatar asked Jul 25 '09 14:07

Kris-I


2 Answers

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
like image 138
JoshJordan Avatar answered Nov 11 '22 05:11

JoshJordan


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
like image 1
Blackspy Avatar answered Nov 11 '22 05:11

Blackspy