首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取字典中某个值的实例数

获取字典中某个值的实例数
EN

Stack Overflow用户
提问于 2013-03-25 22:36:19
回答 2查看 1.6K关注 0票数 0

如何在包含带有lambda表达式的字符串列表的字典中获取值的实例数?

代码语言:javascript
运行
复制
private Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

下面需要改进以消除错误;基本上不能将字符串与字符串列表进行比较。

代码语言:javascript
运行
复制
int count = dict.Values.Count(v => v == "specific value");
EN

Stack Overflow用户

回答已采纳

发布于 2013-03-25 22:43:34

我会使用这个版本:

代码语言:javascript
运行
复制
int count = dict.Count(kvp => kvp.Value.Contains("specific value"));

编辑Ok,这里是比较Contains()方法和SelectMany()方法(x86发布版本)的一些结果:

n1 = 10000,n2 = 50000:

代码语言:javascript
运行
复制
Contains() took: 00:00:04.2299671
SelectMany() took: 00:00:13.0385700
Contains() took: 00:00:04.1634190
SelectMany() took: 00:00:12.9052739
Contains() took: 00:00:04.1605812
SelectMany() took: 00:00:12.8953210
Contains() took: 00:00:04.1356058
SelectMany() took: 00:00:12.9109115

n1 = 20000,n2 = 100000:

代码语言:javascript
运行
复制
Contains() took: 00:00:16.7422573
SelectMany() took: 00:00:52.1070692
Contains() took: 00:00:16.7206587
SelectMany() took: 00:00:52.1910468
Contains() took: 00:00:16.6064611
SelectMany() took: 00:00:52.1961513
Contains() took: 00:00:16.6167020
SelectMany() took: 00:00:54.5120003

对于第二组结果,我将n1和n2都加倍,结果是字符串总数的四倍。

两种算法的时间都增加了4倍,这表明它们都是O(N),其中N是字符串的总数。

和代码:

代码语言:javascript
运行
复制
using System;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;

namespace Demo
{
    public static class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            var dict = new Dictionary<string, List<string>>();
            var strings = new List<string>();

            int n1 = 10000;
            int n2 = 50000;

            for (int i = 0; i < n1; ++i)
                strings.Add("TEST");

            for (int i = 0; i < n2; ++i)
                dict.Add(i.ToString(), strings);

            for (int i = 0; i < 4; ++i)
            {
                var sw = Stopwatch.StartNew();
                dict.Count(kvp => kvp.Value.Contains("specific value"));
                Console.WriteLine("Contains() took: " + sw.Elapsed);

                sw.Restart();
                dict.Values.SelectMany(v => v).Count(v => v == "specific value");
                Console.WriteLine("SelectMany() took: " + sw.Elapsed);
            }
        }
    }
}
票数 5
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15617607

复制
相关文章

相似问题

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