views:

735

answers:

4

Hello,

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,

+11  A: 

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
JoshJordan
I meant to suggest Any too, butI had just woken up and couldn't remember it... stupid mornings!
Telos
A: 

I think either of those work, actually. Keep in mind Visual Studio can't handle Linq Queries in the watch window either, so I suspect the error you saw is more of a Visual Studio problem than the code not working.

Telos
A: 

Try this code to get the count of typeofwork not initialized.

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

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
Blackspy