2013-04-11 55 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