Using C#, how can I convert/iterate a List/Array/Dictionary to a collection which can easily output it's index?
E.g. in Scala I'd use .zipWithIndex in order to convert a list of [a,b,c] to a list of [(a, 0), (b, 1), (c, 2)]
Is there an 'easy' way of doing this with inbuilt .net methods? Via LINQ or otherwise?
Or do I have to use an external functional library, or code my own extension method?
From their docs:
http://www.scala-lang.org/api/2.12.1/scala/collection/immutable/List.html#zipWithIndex:List[(A,Int)]
Example: List("a", "b", "c").zipWithIndex = List(("a", 0), ("b", 1), ("c", 2))
Enumerable.Select
has override that have index:
(new List<string>{"a","b","c"}).Select((value,index) => new {value, index})
Depending on what output you need change new {value, index}
to whatever type you want.
The first answer is cleaner, but I was not even aware of the overload of Select
to use an object's index. I came up with the following answer using the Enumerable.Range
and Zip
methods. I am projecting to a System.ValueTuple
.
var myList = new List<object> { "a", "b", "c" };
Enumerable.Range(start: 0, count: myList.Count)
.Zip(myList, (n, value) => (value, n));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With