2
Dim project = new Project(1)
Dim tasks = Task.GetTasks()
Return <?xml version="1.0" encoding="UTF-8"?>
               <Project xmlns="http://schemas.microsoft.com/project">
                   <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....

Fredrik Mörk
  • 151,624
  • 28
  • 285
  • 338
Shawn
  • 18,847
  • 20
  • 96
  • 151

3 Answers3

5

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">
                   <Name><%= project.name %></Name>
                   <Tasks>
                       <%= tasks.Select(Function(t, idx) _
                           <Task>
                               <ID><%= idx + 1 %></ID>                               
                           </Task> _
                           ) %>
                   </Tasks>
mmx
  • 402,675
  • 87
  • 836
  • 780
2

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
  • 976,458
  • 251
  • 2,474
  • 2,830
1

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

Community
  • 1
  • 1
Scott Ivey
  • 39,608
  • 21
  • 79
  • 117