2009-07-25 186 views
7

我有一個「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中的 「立即窗口」,但我收到的錯誤:在這兩個表達式不能包含查詢表達式案例

您有想法嗎?

謝謝,

回答

19

正是錯誤說的。您不能在立即窗口中使用LINQ查詢,因爲它們需要編譯lambda函數。嘗試實際代碼中的第一行,它可以被編譯。 :)

此外,爲了得到這一切在一行完成後,你可以使用LINQ「任何」運算符,就像這樣:

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

我覺得無論這些工作,其實。請記住,Visual Studio無法在監視窗口中處理Linq查詢,所以我懷疑你看到的錯誤更多的是Visual Studio問題,而不是代碼不工作。

0

試試這個代碼來獲得未初始化的typeofwork的計數。

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

怎麼樣

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 
相關問題