Auto Increment Number LINQ to Objects

This seems like a completely basic question, but, in my opinion, I cannot work out an elegant solution.

Basically, I am making a LINQ query creating a new object from the query. In a new object, I want to generate an automatically increasing number so that I can keep the selection order for later use (named Iter in my example).

Here is my current solution that does what I need:

  Dim query2 = From x As DictionaryEntry In MasterCalendarInstance _ Order By x.Key _ Select New With {.CalendarId = x.Key, .Iter = 0} For i = 0 To query2.Count - 1 query2(i).Iter = i Next 

Is there a way to do this in the context of a LINQ query (so I don't need to loop the collection after the query)?

+6
linq-to-objects
source share
4 answers

Sorry I am doing this in C #, not sure about the exact syntax in VB.NET:

 MasterCalendarInstance .OrderBy(x => x.Key) .Select((x, ixc) => new { CalendarId = x.Key, Iter = ixc }); 
+29
source share

I don't know if this is possible in VB, but closure is used in C # 1:

 int count = 0 var res = from x in MasterCalendarInstance order by x.Key select new { CalendarId = x.Key, Iter = count++ }; 
+7
source share

The above solutions could be summarized in VB.NET as follows:

 MasterCalendarInstance _ .OrderBy(Function (x) x.Key) _ .Select(Function (x, ixc) New With { .CalendarId = x.Key, .Iter = ixc }) 
+1
source share

I came across this post trying to solve a similar list issue (String).

I post my workaround in the hope that it can be taken to solve your problem, but more for those who are faced with this problem with a list (Of T).

 Dim list As New List(Of String) list.Add("Test1") list.Add("Test2") list.Add("Test3") Dim var = list.Select(Function(s) New With {.Name = s, .RecordID = list.IndexOf(s)}) 

Hope this helps!

0
source share

All Articles