tags:

views:

42

answers:

3
Dim project = new Project(1)
Dim tasks = Task.GetTasks()
Return <?xml version="1.0" encoding="UTF-8"?>
               <Project xmlns="http://schemas.microsoft.com/project"&gt;
                   <Name><%= project.name %></Name>
                   <Tasks>
                       <%= tasks.Select(Function(t) _
                           <Task>
                               <ID><%= tasks.IndexOf(t) + 1 %></ID>                               
                           </Task> _
                           ) %>
                   </Tasks>
               </Project>

I am trying to replace tasks.IndexOf(t) + 1 with something a little simpler. Is there any built in functionality for this?

Hrmm xml literals do not seem to translate well on here....

+4  A: 

There's an overload for Enumerable.Select that supports passing an index along with the object itself. You can use that one:

Dim project = new Project(1)
Dim tasks = Task.GetTasks()
Return <?xml version="1.0" encoding="UTF-8"?>
               <Project xmlns="http://schemas.microsoft.com/project"&gt;
                   <Name><%= project.name %></Name>
                   <Tasks>
                       <%= tasks.Select(Function(t, idx) _
                           <Task>
                               <ID><%= idx + 1 %></ID>                               
                           </Task> _
                           ) %>
                   </Tasks>
Mehrdad Afshari
+1  A: 

You could use the Select overload that uses an indexer. See this answer for something similar

Scott Ivey
+1  A: 

There is an overload of Select that takes a Func<TSource, int, TResult> (i.e. a Function(t,i) or (t,i) => {...}) - the int is the index.

Marc Gravell