【问题标题】:Converting Lookup<TKey, TElement> into other data structures c#将 Lookup<TKey, TElement> 转换为其他数据结构 c#
【发布时间】:2012-07-08 13:07:41
【问题描述】:

我有一个

Lookup<TKey, TElement>

其中 TElement 指的是一串单词。我想转换 查找:

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

我已经阅读了一些关于使用的文章

Lookup<TKey, TElement>

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

【问题讨论】:

    标签: c# c#-4.0 lookup


    【解决方案1】:

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

    假设您有一个名为 mylookupLookup&lt;int, string&gt; 包含多个单词的字符串,那么您可以将 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);
        }
    }
    

    此外,如果顺序很重要,您始终可以通过OrderByOrderByDescending 扩展方法对IEnumerables 进行排序。

    编辑:

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

    【讨论】:

    • @Qaesar:我猜你在这里指的是你的另一个问题(stackoverflow.com/questions/11378338/…),对吧?你有一个Lookup&lt;int, string&gt;。你到底想达到什么目标?
    • 是的,完全正确。我想根据单词长度对一串单词进行分组。那么哪种结构更可取?我可以继续使用 Lookup 吗?因为在那之后我会将每个 TElement(单词数组)写入 excel 列。
    • 不完全是,ToLoopup 方法返回一些带有ILookup 接口的对象。您的方法如下所示:private ILookup&lt;int, string&gt; WordGrouping(string input) { return input.Trim().Split().Distinct().ToLookup(word =&gt; word.Length); }
    • @Qaesar:不,它不只返回计数,而是返回包含计数和单词列表的分组列表,就像我已经解释的那样。 string.Split 永远不能包含 null 值,因此错误肯定在其他地方。这与最初的问题相去甚远。如果仍有问题,请提出新的 stackoverflow 问题。
    • @Philip Daubmeier:+1,感谢您的无限耐心。
    【解决方案2】:

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

    TKey key;
    Lookup<TKey, TValue> lookup;
    IEnumerable<TValue> values = lookup[key];
    

    由于它实现了IEnumerable&lt;IGrouping&lt;TKey, TValue&gt;&gt;,您可以使用可枚举的扩展方法将其转换为您想要的结构:

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

    【讨论】:

    • 谢谢!!对于“值 = 查找 [键]”。其他人都在说,“嘿,你可以遍历结果”,而我已经准备好放弃将查找结果 Linq 到一个数组中。
    猜你喜欢
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多