views:

869

answers:

4

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 am needing:

     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)? Thanks!

A: 

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++
          };
Richard
See other answer: this /is/ possible...
Richard
This was my first inclination (Gerneraly, I am a c# dude). However, I am not aware of any vb.net version of ++ . I was tempted to stick in a delegate method to handle this, but that adds more complication than I prefer in such a simple task.
Nathan
+7  A: 

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 });
veggerby
I don't quite see how this solves my problem. how does the ixc value get populated and auto-incremented?
Nathan
automagically :) it is an overload for the .Select extension method which takes a Func<T, int, TResult> (see http://msdn.microsoft.com/en-us/library/bb534869.aspx)
veggerby
Thanks this solved my problem. I appreciate the help!
Nathan
D'oh. +1 for reading the docs :)
David Schmitt
A: 

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!

Airn5475
A: 

int count = 0; var res = from x in mx.SUP_ACCOUNT_MATCH orderby x.EntityKey select new { CalendarId = x.EntityKey, Iter = count++ };

This will not work. I have tried it. You get an error saying "An expression tree cannot have an assignment operator"

Sandeep