将Lookup <TKey,TElement>转换为其他数据结构c#

FSm*_*FSm 10 c# lookup c#-4.0

我有一个

Lookup<TKey, TElement>
Run Code Online (Sandbox Code Playgroud)

TElement指的是一串单词.我想将Lookup转换为:

Dictionary<int ,string []> or List<List<string>> ?
Run Code Online (Sandbox Code Playgroud)

我读过一些关于使用的文章

Lookup<TKey, TElement>
Run Code Online (Sandbox Code Playgroud)

但这还不足以让我理解.提前致谢.

Phi*_*ier 15

您可以使用以下方法执行此操作:

假设您有一个包含多个单词的字符串Lookup<int, string>调用mylookup,那么您可以将IGrouping值放入a string[]并将整个内容打包到字典中:

var mydict = mylookup.ToDictionary(x => x.Key, x => x.ToArray());
Run Code Online (Sandbox Code Playgroud)

更新

阅读完您的评论后,我知道您的查询实际上要做什么(请参阅上一个问题).您不必将其转换为字典或列表.只需直接使用查找:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果订单很重要,您始终可以IEnumerable通过OrderByOrderByDescending扩展方法对s进行排序.

编辑:

查看上面编辑过的代码示例:如果要订购密钥,只需使用该OrderBy方法即可.您可以使用相同的方式按字母顺序排序单词grouping.OrderBy(x => x).

  • @Philip Daubmeier:+1为你无尽的耐心. (2认同)

Lee*_*Lee 5

查找是从键到值集合的映射集合。给定一个键,您可以获得相关值的集合:

TKey key;
Lookup<TKey, TValue> lookup;
IEnumerable<TValue> values = lookup[key];
Run Code Online (Sandbox Code Playgroud)

当它实现时,IEnumerable<IGrouping<TKey, TValue>> 您可以使用可枚举的扩展方法将其转换为您想要的结构:

Lookup<int, string> lookup = //whatever
Dictionary<int,string[]> dict = lookup.ToDictionary(grp => grp.Key, grp => grp.ToArray());
List<List<string>> lists = lookup.Select(grp => grp.ToList()).ToList();
Run Code Online (Sandbox Code Playgroud)