Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of Scala List's Zip with Index?

Tags:

c#

scala

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))

like image 471
Ryan Leach Avatar asked Apr 06 '18 03:04

Ryan Leach


2 Answers

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.

like image 120
Alexei Levenkov Avatar answered Sep 20 '22 10:09

Alexei Levenkov


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));
like image 21
MJB Avatar answered Sep 19 '22 10:09

MJB