我有一个
Lookup<TKey, TElement>
其中 TElement 指的是单词字符串。我想转换 查找:
Dictionary<int ,string []> or List<List<string>> ?
我读过一些有关使用的文章
Lookup<TKey, TElement>
但这对我来说还不够理解。提前致谢。
最佳答案
您可以使用以下方法来做到这一点:
假设您有一个Lookup<int, string>
叫mylookup
对于包含多个单词的字符串,那么您可以将 IGrouping
值到 string[]
并将整个内容打包到字典中:
var mydict = mylookup.ToDictionary(x => x.Key, x => x.ToArray());
更新
读完您的评论后,我知道您实际上想对查找执行什么操作(请参阅操作 previous question )。您不必将其转换为字典或列表。直接使用查找即可:
var wordlist = " aa bb cc ccc ddd ddd aa ";
var lookup = wordlist.Trim().Split().Distinct().ToLookup(word => word.Length);
foreach (var grouping in lookup.OrderBy(x => x.Key))
{
// grouping.Key contains the word length of the group
Console.WriteLine("Words with length {0}:", grouping.Key);
foreach (var word in grouping.OrderBy(x => x))
{
// do something with every word in the group
Console.WriteLine(word);
}
}
此外,如果顺序很重要,您可以随时对 IEnumerable
进行排序。通过OrderBy
或OrderByDescending
扩展方法。
编辑:
查看上面编辑后的代码示例:如果您想订购 key ,只需使用 OrderBy
方法。同样,您可以使用 grouping.OrderBy(x => x)
按字母顺序对单词进行排序。 .
关于c# - 将 Lookup<TKey, TElement> 转换为其他数据结构 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11383384/