Reputation: 319
I am trying to get values from a list. In the result I need the index of the value in the resulting list also. I dont have any idea how to get it. Can someone get me some ideas. Following is the code which i use.
List<string> Lst1 = new List<string>();
Lst1.Add("a");
Lst1.Add("ab");
Lst1.Add("c");
Lst1.Add("d");
List<string> result = Lst1.Select(x => x.Substring(0, 1)).ToList();
Upvotes: 0
Views: 82
Reputation: 21795
You can use second overload of Enumerable.Select:-
var result = Lst1.Select((v, i) => new { Value = v, Index = i });
Upvotes: 1
Reputation: 387527
Enumerable.Select has an overload that gives the index too, so you can just use that. Note that you cannot store both the string and the index in a List<string>
, so you maybe need a List<Tuple<string, int>>
instead. Also note, that in a list, each element already has an index, so you don’t really need this anyway.
List<Tuple<string, int>> result = Lst1.Select(
(x, i) => new Tuple<string, int>(x.Substring(0, 1), i)).ToList();
Upvotes: 4