简体   繁体   中英

Linq to entities - include foreach inside query

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"?

Of course you can! Here you will find examples:

http://www.dotnetperls.com/todictionary

in your case:

.ToDictionary(v => v.ProductName, v => v.ProductTitle)

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 the ForEach method, however the cleanest way would be to use the LINQ ToDictionary method .

var productNames = 
 from product in entities.tbl_producttype
  select new { ProductName = product.Name, ProductTitle = product.TitleName };
var allItemNames = 
 productNames 
  .ToDictionary(product => product.ProductName, product => product.ProductTitle);

使用ToDictionary

allItemNames = productNames.ToDictionary(p => p.Name, p => p.ProductTitle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM