2013-04-11 58 views
0

我有「的字符串,DeviceInfo」,其中DeviceInfo是包含一些屬性一類的字典,如下圖所示:使用LINQ以選擇它們匹配列表,表中的項目

public string Name { get; set; } 
    public string Id { get; set; } 
    public bool Actioned { get; set; } 

我需要使用LINQ實體從字典中的DeviceInfo「Name」屬性中存在表中的deviceId的表中選擇設備詳細信息。類似於以下的是我所追求的。不幸的是我的代碼不起作用。任何人都會告訴我我要去哪裏?

from t in _context.Devices where list.Select(x => x.Value.Name).Contains(t.DeviceId) select t 
+0

你用'.Contains(「」+ t.DeviceId)''試過了嗎?我不確定它是否會這樣工作,但它值得一試。 – IronMan84 2013-04-11 15:36:25

回答

1

從字典中獲取簡單List<string>Name S:

var names = list.Select(x => x.Value.Name).ToList(); 

然後你的LINQ中使用它來Entities查詢:

from t in _context.Devices 
where names.Contains(t.DeviceId) 
select t 

或用SqlFunctions.StringConvert如果您DeviceId是和int

from t in _context.Devices 
where names.Contains(SqlFunctions.StringConvert((double)t.DeviceId)) 
select t 

它應該在SQL查詢中生成IN語句。

+0

你好,謝謝。我曾嘗試將名稱放入單獨的列表中,但顯然得到了linq的第二位錯誤,因爲您的解決方案正常工作。爲我節省了很多時間,再次感謝。 – Retrocoder 2013-04-12 07:35:28

+0

我發現我可以避免在名單上使用「ToList」,希望能夠提高性能。 – Retrocoder 2013-04-12 07:42:05

+0

@Retrocoder是的,你可以省略'ToList()',但我不會這樣做,因爲這會不同的sql查詢執行,並會使其他方法中的查詢可能中斷。你可以嘗試使用'AsEnumerable()'而不是'ToList()'來獲得sql查詢安全的緩存執行。 – MarcinJuraszek 2013-04-12 07:45:29