-1

I would like to access the row number in linq query. There are many articles on the web stating how to do this but there is a catch: I want to resolve the enumeration "later" and I want it to assign the same ID every time. For this reason methods such as this do not work:

public IEnumerable<MyClass> GetThings(List<object> lst)
{
  int ID=0;
  return from i in lst
         select new MyClass(ID++, i);
}
public class MyClass
{
  public MyClass(int ID, object Stuff)
  { ... }
}
...
  var x = GetThings(SomeList);

(fails because each time you resolve x by iterating each item gets a different id)

DJL
  • 2,060
  • 3
  • 20
  • 39

2 Answers2

1

Turns out the solution to this is quite simple - grab the row number of the source collection, not the output collection. Obviously this only works if you are not filtering etc. and the number of items in your output collection is the same as the input collection. Unless you're ok with gaps and/or duplicates

i.e.

public IEnumerable<MyClass> GetThings(List<object> lst)
{
  int ID=0;
  return from i in lst.Select((item,id)=>new {Item=item, ID=id})
         select new MyClass(i.ID, i.Item);
}
public class MyClass
{
  public MyClass(int ID, object Stuff)
  { ... }
}
...
  var x = GetThings(SomeList);

now the ID's of each item in x is the same every time you iterate it

DJL
  • 2,060
  • 3
  • 20
  • 39
1

Actually you can use the Select overload that pass the index too, something like this:

lst.Select((o, i) => new MyClass(i, o));
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • Actually on closer inspection I could apply this shorter solution in my real-world application too. Nice :) – DJL Apr 21 '16 at 14:44