views:

38

answers:

2

I have an array of Car objects and using the following piece of code I create an XML Document from these objects. I have set up a counter variable i to be able to index the Car elements in the document. Is there a different way of obtaining the index of the currently processed element?

        int i = 0;
        XDocument doc =
            new XDocument(
                new XElement(
                    "Inventory",
                    from car in cars
                    select
                        new XElement("Car",
                            new XAttribute("ID", ++i), //<<== index here
                            new XElement("Color", car.Color),
                            new XElement("Make", car.Make),
                            new XElement("PetName", car.PetName)
                        )
                )
            );

The approach I have taken works fine, I am just wondering whether there's a magic word or extension method that will yield the index without my incrementing a counter variable?

+2  A: 

Yup - don't use a query expression; use the overload of Select which provides an index. This replaces your query expression:

cars.Select((car, index) =>
    new XElement("Car",
        new XAttribute("ID", index),
        new XElement("Color", car.Color),
        new XElement("Make", car.Make),
        new XElement("PetName", car.PetName)
    ))

There are various overloads which aren't supported in query expressions - it's definitely worth being familiar with both "dot notation" (or whatever you want to call it) and query expressions.

Jon Skeet
+2  A: 

There is an overload of Select which takes an index so you can change your query expression to this:

cars.Select((c, i) => new XElement("Car", new XAttribute("ID", i) ...))
Lee