使用LINQ查询多个表,将结果抓取到字典
c#
我有这个简单的 SQL:
SELECT name, value
FROM table1 t1, table2 t2
WHERE t1.id = t2.id
AND t1.id = 123
如何在 C# 中将其转换为 LINQ,以便结果在 Dictionary 中?
回答
我猜你在使用实体框架?你可以改用RelationShips吗?
或者像这样:
var query = from t1 in context.Table1
from t2 in context.Table2
where t1.Id == t2.Id
select new { t1.name, t2.value};
var result = query.ToList();
var dir = result.ToDictionary(x => x.name, x => x.value);
https://docs.microsoft.com/en-us/ef/core/querying/complex-query-operators
- 为什么 `ToList` 它有什么用途,你可以直接将 enumerable 传递给 `ToDictionary`