0

.NET version 4.0, language: C# (VS 2010)

C# "fluent" syntax for LINQ gives the following option for Select, where the predicate has two arguments - the item in the list itself, and the index of the item in the list.

Very stripped out generic example of the kind of thing I'm doing:

List<string> MyList = new List<string>{ "foo", "bar", "baz" };

var nodes = MyList.Select( 
    (item, indexInList) => 
    new XElement("p", new XAttribute("id", indexInList + 1 ), item)
);

output is XElements representing

<p id=1>foo</p>
<p id=2>bar</p>
<p id=3>baz</p>

This works, meets requirements, no issues there. However. Our department standards prefer query syntax, and personally I find it easier to read. Is it possible to express the above in query syntax?

My instinct was to try the following by analogy but VS didn't like it at all.

var nodes = from (item, indexInList) in MyList
            select new XElement("p", new XAttribute("id", indexInList + 1), item);

I've been googling back and forth and I keep getting questions about "given XYZ quantifiers, find the index of a single matching item" - I don't want that. I want one-or-many matching items and their indexes.

Jerril
  • 17
  • 4
  • no, you shouldn't necessarily prefer one syntax over the other. but query syntax is more limited than the method syntax, so i personally would advise that instead. – DLeh May 12 '15 at 14:43
  • I have never managed to figure out how to use it but apparently LinqPad can give you the answer. Everyone I know who have used it say its really good and easy to use. – Keithin8a May 12 '15 at 14:44
  • @DLeh etc - thanks for finding the answering question. Is there something I should do to mark this as solved? – Jerril May 12 '15 at 14:55
  • @Jerril nope! it has been marked as duplicate, so any others who come across this question will see that and look at that duplicate to find their answer. Welcome to Stack Overflow! – DLeh May 12 '15 at 15:25

0 Answers0