微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何在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}",string.Join(",g.Customers.Select((x,i) => i + ". " + x.CompanyName).ToArray())));

原文地址:https://www.jb51.cc/csharp/98216.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐