首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将SortedDictionary子集作为SortedDictionary获取

将SortedDictionary子集作为SortedDictionary获取
EN

Stack Overflow用户
提问于 2011-02-09 08:46:52
回答 1查看 2.9K关注 0票数 2

在C#中,如何使用LINQ对SortedDictionary进行筛选,生成一个子集(也是SortedDictionary )?例如:我想写信

代码语言:javascript
复制
SortedDictionary<int, Person> source = ..fetch..
SortedDictionary<int, Person> filtered = source.Where(x=>x.foo == bar)

我发现的唯一方法是创建一个助手方法并使用它

代码语言:javascript
复制
SortedDictionary<TKey, TValue> SubDictionary<TKey, TValue> IEnumerable<KeyValuePair<TKey, TValue>> l) 
{
    SortedDictionary<TKey, TValue> result = new SortedDictionary<TKey, TValue>();
    foreach (var e in l)
      result[e.Key] = e.Value;
    return result;
}

...

SortedDictionary<int, Person> source = ..fetch..
SortedDictionary<int, Person> filtered = SubDictionary(source.Where(x=>x.foo == bar))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-09 09:22:20

如果您想要一个单语句解决方案,这将有效:

代码语言:javascript
复制
SortedDictionary<int, Person> filtered = 
    new SortedDictionary<int, Person>(
        source.Where(x => x.Value.foo == bar)
              .ToDictionary(kvp => kvp.Key, kvp => kvp.Value));

但是,它效率低下,因为它创建了两个字典对象( ToDictionary()扩展方法创建了一个,然后传递给SortedDictionary构造函数)。

您的助手方法将带来更好的性能。为了获得更清晰的语法,您可以将其作为IEnumerable>上的扩展方法:

代码语言:javascript
复制
public static class KeyValuePairEnumerableExtensions
{
    public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(
        this IEnumerable<KeyValuePair<TKey, TValue>> l)
    {
        SortedDictionary<TKey, TValue> result = new SortedDictionary<TKey, TValue>();
        foreach (var e in l) 
            result[e.Key] = e.Value;
        return result;
    }
}

可以这样使用:

代码语言:javascript
复制
var f2 = source.Where(x => x.Value.foo == bar).ToSortedDictionary();
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4942827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档