c# - 如何访问 LINQ 选择中的循环索引?

标签 c# linq

这段代码:

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())));

关于c# - 如何访问 LINQ 选择中的循环索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1681715/

相关文章:

c# - 如何在 C# 中读取 USB (PnP) 设备的 WMI 数据,在本例中为硬件 ID?

c# - 适用于 Windows 和 Windows Mobile 的通用 C# 源代码

c# - 使用 C# 从 MySQL 数据库中的 JSON 响应插入日期时间

c# - 如何使 Xamarin.Forms.iOS View 滚动到焦点所在的条目?

c# - 查询数据库中的每条记录比使用 LINQ 更快

c# - 如何获取 List<T> 的前一个元素

c# - 使用 C# 解析复杂的 JSON

c# - 如何通过 MVVM 在 WPF Web 浏览器控件上使用 Javascript

c# - 我的 EF 查询有什么问题?

c# - 使用 Linq 解析 XML 时,只会获取一个对象