我有一个从字典文件中读入的字符串列表(按字母顺序排序).我想创建每个起始字母的最后一个位置的索引,所以如果有1000个以A开头的单词,它将被记录为位置999(因为数组从0开始).以B开头的1000个单词意味着B的结束位置是1999年,依此类推.这些位置值将存储在int数组中.
我能想到的唯一方法就是循环遍历整个列表,并且还有很多if语句来查看单词的第一个字母.不是最优雅的解决方案.
有没有人知道一个简单的方法来做到这一点,而不是26个if语句?
编辑:这样做的目的是生成随机单词.如果我想要以BI开头的单词将生成1000到1999之间的随机数,并从列表中的该位置获取单词.
好吧,你可以使用LINQ创建一个字典:
// Note: assumes no empty words
Dictionary<char, int> lastEntries = words
.Select((index, value) => new { index, value })
.GroupBy(pair => pair.value[0])
.ToDictionary(g => g.Key, g => g.Max(p => p.index));
Run Code Online (Sandbox Code Playgroud)
或者更有用的是,保留第一个和最后一个索引:
Dictionary<char, Tuple<int, int>> entryMinMax = words
.Select((value, index) => new { value, index })
.GroupBy(pair => pair.value[0])
.ToDictionary(g => g.Key,
g => Tuple.Of(g.Min(p => p.index), g.Max(p => p.index));
Run Code Online (Sandbox Code Playgroud)
或者,如果要点是用第一个字母有效地对单词进行分组,那么只需使用查找:
ILookup<char, string> lookup = words.ToLookup(word => word[0]);
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
char first = 'B'; // Or whatever
Random rng = new Random(); // But don't create a new one each time...
var range = lookup[first];
var count = range.Count();
if (count == 0)
{
// No words starting with that letter!
}
int index = random.Next(count);
var randomWord = range.ElementAt(index);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |