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
  • 155,851
  • 29
  • 291
  • 343
Shawn
  • 19,465
  • 20
  • 98
  • 152

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>
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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

Community
  • 1
  • 1
Scott Ivey
  • 40,768
  • 21
  • 80
  • 118