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

本文关键字:实例 字典 获取 | 更新日期: 2023-09-27 18:05:37

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

private Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
下面

需要改进以消除错误;基本上不能比较字符串和字符串列表

int count = dict.Values.Count(v => v == "specific value");

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

我会使用这个版本:

int count = dict.Count(kvp => kvp.Value.Contains("specific value"));

[EDIT]好的,这里是Contains()方法和SelectMany()方法(x86发行版本)的一些比较结果:

n1 = 10000, n2 = 50000:

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:

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是字符串的总数。

和代码:

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

using linq ?当然。

 dict.Values.SelectMany( v => v).Where( v => v == "specific value").Count();

即:

dict.Values.SelectMany( v => v).Count(  v => v == "specific value" );