Fast and efficient iterator in C #

I have a set of words and would like to assign a unique int value to each one. I've been reading about LINQ for a while and came up with this:

var words = File.ReadAllLines(wordsFile);
var numbers = Enumerable.Range(1, words.Count());
var dict = words
    .Zip(numbers, (w, n) => new { w, n })
    .ToDictionary(i => i.w, i => i.n);

      

The question arises:

  • Is this a good approach? Is it efficient in terms of performance?
  • Is there a better way to do this in terms of simplicity (clear code)?
+3


source to share


1 answer


You don't need the approach Enumerable.Range

and Zip

, since you can use an overload Select

that gives you the index:



var dict = File.ReadLines(wordsFile)
    .Select((word, index) => new { word, index })
    .ToDictionary(x => x.word, x => x.index + 1);

      

+6


source







All Articles