tags:

views:

95

answers:

2

This code:

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

yields these results:

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
...

How can I replace the "#" with an index/count so that I get results like these:

Argentina has 3 customers: 1. Cactus Comidas para llevar, 2. Océano Atlántico Ltda., 3. Rancho grande
...
+6  A: 
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())));
LukeH
Very interesting, that works, where is i being incremented actually?
Edward Tanguay
@Edward: Take a look at this. It explains the LINQ SELECT with a two parameter lambda. http://weblogs.asp.net/fmarguerie/archive/2008/11/10/using-the-select-linq-query-operator-with-indexes.aspx
Trevor Tippins
@Edward, i is being incremented internally in the Select extension method and the new value is passed down for each value.
JaredPar
A: 

Try making an int x = 0; prior to your linq statement. Then, within, print (x++).ToString().

This will make x a closure.

uosɐſ