Nathan
Nathan

Reputation: 1435

LINQ to Objects auto increment number

This feels like a completely basic question, but, for the life of me, I can't seem to work out an elegant solution.

Basically, I am doing a LINQ query creating a new object from the query. In the new object, I want to generate a auto-incremented number to allow me to keep a 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 within the context of the LINQ query (so that I don't have to loop the collection after the query)?

Upvotes: 7

Views: 22037

Answers (4)

Invvard
Invvard

Reputation: 2047

The above solutions could be summed up in VB.NET like this :

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

Upvotes: 1

Airn5475
Airn5475

Reputation: 2492

I ran into this post while trying to solve a similar problem with a List(of String).

I'm posting my workaround in hopes that it may be adopted to resolve your issue, but more for anyone else who runs into this issue 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!

Upvotes: 0

veggerby
veggerby

Reputation: 9020

Pardon me for doing this in C# not sure exactly the syntax in VB.NET:

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

Upvotes: 36

Richard
Richard

Reputation: 109100

I don't know if this is possible in VB, but in C# one uses a closure:

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

Upvotes: 9

Related Questions