我有一个单词集合,并希望为每个单词分配一个唯一的int值.我已经阅读了一段时间的LINQ并想出了这个:
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);
Run Code Online (Sandbox Code Playgroud)
问题是:
您不需要Enumerable.Range和Zip方法,因为您可以使用Select为您提供索引的重载:
var dict = File.ReadLines(wordsFile)
.Select((word, index) => new { word, index })
.ToDictionary(x => x.word, x => x.index + 1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |