转换查找< TKEY的,TElement>到其他数据结构C# [英] Converting Lookup<TKey, TElement> into other data structures c#

查看:242
本文介绍了转换查找< TKEY的,TElement>到其他数据结构C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

Lookup<TKey, TElement>



其中TElement指一串字。我想
查找转换为:

where the TElement refers to a string of words. I want to convert Lookup into:

Dictionary<int ,string []> or List<List<string>> ?



我读过关于使用

I have read some articles about using the

Lookup<TKey, TElement>



但它是不够的,我明白。提前致谢。

but it wasn't enough for me to understand. Thanks in advance.

推荐答案

您可以做到这一点使用这些方法:

You can do that using these methods:

  • Enumerable.ToDictionary<TSource, TKey>
  • Enumerable.ToList<TSource>

让说你有一个查找< INT,串> 名为 mylookup 包含几个单词的字符串,那么你可以把 IGrouping 值到的String [] 和包装整个事情变成词典:

Lets say you have a Lookup<int, string> called mylookup with the strings containing several words, then you can put the IGrouping values into a string[] and pack the whole thing into a dictionary:

var mydict = mylookup.ToDictionary(x => x.Key, x => x.ToArray());



更新

看了你的评论,我知道你其实想与你的查找(见OPS的前面的问题)。你不必把它转换成一个字典或列表。只需直接使用查找:

Having read your comment, I know what you actually want to do with your lookup (see the ops previous question). You dont have to convert it into a dictionary or list. Just use the lookup directly:

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);
    }
}



此外,如果顺序很重要,可以随时排序通过排序依据 OrderByDescending 扩展方法的的IEnumerable 取值

编辑:

看上面编辑的代码示例:如果您要订购的钥匙,只需要使用排序依据方法。

look at the edited code sample above: If you want to order the keys, just use the OrderBy method. The same way you could order the words alphabetically by using grouping.OrderBy(x => x).

这篇关于转换查找&LT; TKEY的,TElement&GT;到其他数据结构C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆