如何访问LINQ select中的循环索引? [英] How can I access the loop index inside a LINQ select?
本文介绍了如何访问LINQ select中的循环索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码:
var customers = from cust in Customers
group cust by new {cust.Country} into grouping
select new
{
Country = grouping.Key.Country,
Customers = grouping
};
customers.ToList().ForEach(g =>
Console.WriteLine("{0} has {1} customers: {2}",
g.Country,
g.Customers.Count(),
String.Join(", ",g.Customers.Select(x => "#. " + x.CompanyName).ToArray())
));
customers.Dump();
产生以下结果:
Argentina has 3 customers: #. Cactus Comidas para llevar, #. Océano Atlántico Ltda., #. Rancho grande
Austria has 2 customers: #. Ernst Handel, #. Piccolo und mehr
Belgium has 2 customers: #. Maison Dewey, #. Suprêmes délices
Brazil has 9 customers: #. Comércio Mineiro, #. Familia Arquibaldo, #. Gourmet Lanchonetes, #. Hanari Carnes, #. Que Delícia, #. Queen Cozinha, #. Ricardo Adocicados, #. Tradição Hipermercados, #. Wellington Importadora
Canada has 3 customers: #. Bottom-Dollar Markets, #. Laughing Bacchus Wine Cellars, #. Mère Paillarde
Denmark has 2 customers: #. Simons bistro, #. Vaffeljernet
...
如何用索引/计数替换#",以便获得如下结果:
Argentina has 3 customers: 1. Cactus Comidas para llevar, 2. Océano Atlántico Ltda., 3. Rancho grande
...
推荐答案
customers.ToList().ForEach(g => Console.WriteLine("{0} has {1} customers: {2}",
g.Country,
g.Customers.Count(),
string.Join(", ",
g.Customers.Select((x, i) => i + ". " + x.CompanyName).ToArray())));
这篇关于如何访问LINQ select中的循环索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文