Linq toEntity - 在查询中包含 foreach
我创建了以下代码:
Dictionary<string, string> allItemNames = new Dictionary<string, string>();
var productNames = from product in entities.tbl_producttype
select new { ProductName = product.Name, ProductTitle = product.TitleName };
foreach (var productName in productNames)
{
allItemNames.Add(productName.ProductName, productName.ProductTitle);
}
它工作得很好,但是我可以通过删除“foreach”短语并使查询插入到字典中来缩短代码吗?就像 linq 的某种“into”短语告诉查询“将 ProductName 插入到字典的第一个字符串中,将 ProductTitle 插入到第二个字符串中”?
i created the following code:
Dictionary<string, string> allItemNames = new Dictionary<string, string>();
var productNames = from product in entities.tbl_producttype
select new { ProductName = product.Name, ProductTitle = product.TitleName };
foreach (var productName in productNames)
{
allItemNames.Add(productName.ProductName, productName.ProductTitle);
}
it works great, but can i make the code shorter by dropping the 'foreach' phrase and make the query do the insert into the dictionary? like some kind of an 'into' phrase of the linq that tells the query to "insert the productName into the first string of the dictionary and the ProductTitle into the second"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然可以!在这里您可以找到示例:
http://www.dotnetperls.com/todictionary
在您的情况下:
Of course you can! Here you will find examples:
http://www.dotnetperls.com/todictionary
in your case:
它可能会混淆代码以在查询时进行修改。您当前的实现易于阅读并表达了循环的意图。因此,Enumerable 上没有方法可以执行此操作。
在
List
上,您可以使用ForEach
方法,但最简洁的方法是使用 LINQ ToDictionary 方法。It can confuse code to make modifications whilst querying. Your current implementation is easily readable and expresses the intent of the loop. As such there is no method on an Enumerable to do this.
On a
List
you could use theForEach
method, however the cleanest way would be to use the LINQ ToDictionary method.使用ToDictionary:
using
ToDictionary
: