开发者

Get access to an incrementing integer during LINQ Select

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 xm开发者_StackOverflowl literals do not seem to translate well on here....


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>


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜