-1

Let's say I have this line for a type X and a List<X> lx :

Dict<string, X> d = lx.ToDictionary(x => F(Z.g(x).ToString()), x => x)

where Z is a type with static member function Y g( X x) where Yis a type implementing ToString.

Now I change Y g( X x) into Y g( X x, T t) where T is some type . Let's say I have a List<T> lt with same Count as lx. I would like to change my previous line into (warning, pseudo code) a line :

Dict<string, X> d = lx.ToDictionary(x => F(Z.g(x, something).ToString()), x => x)

where in the expression something I get the index i of the x inside lx, index to which I associate lt[i].

Olórin
  • 3,367
  • 2
  • 22
  • 42
  • 2
    Please make an actual [mcve], your abbreviated method names and variables make your code very difficult to parse. And why abbreviate `Dict`?! – DavidG Aug 02 '17 at 09:27
  • @CodeCaster if it's duplicate, I would be glad to see the initial same question, as I didn't succeed in finding it after looking for it ... Thx in advance – Olórin Aug 02 '17 at 09:30
  • In the yellow box at the top of your question. – CodeCaster Aug 02 '17 at 09:32
  • 1
    For the purposes of your problem, `F(Z.g(x).ToString())` is the same as `f(x)`. These unnecessary abbreviated function names really distract from the actual functionality, which is `var d = list.ToDictionary(x => f(x), x => x)`. So your actual simple question would be "how to get `list.ToDictionary(x => f(x, index_of_x), x => x)`", and that is answered in the [duplicate](https://stackoverflow.com/q/9847547/69809). – vgru Aug 02 '17 at 09:32
  • @CodeCaster As of now, no link to any question appears on my side in the yellow box. – Olórin Aug 02 '17 at 09:35
  • "top of your question" – vgru Aug 02 '17 at 09:36
  • 1
    https://i.stack.imgur.com/cztSP.png – CodeCaster Aug 02 '17 at 09:36

1 Answers1

0

You can use Select to get the index of the item within the collection:

lx.Select((item, index) => new { Item = item, Index = index })
  .ToDictionary(...);

Here I construct an anonymous type to hold both the item and the index, which you can use in the following lambdas.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • It will give me the correct index even if `lt[i]` appears at several positions in `lt` ? (`T = string` in my case.) – Olórin Aug 02 '17 at 09:29
  • 1
    @ujsgeyrr1f0d0d0r0h1h0j0j_juj: this merely iterates through the list and creates a tuple (item, index) for each item. So each item in the list will be processed, yes. – vgru Aug 02 '17 at 09:30
  • Not sure what that means. Can you test this code and see if that is what you expected? – Patrick Hofman Aug 02 '17 at 09:30