0

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

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

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

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

2 回答 2

5

使用 linq 吗?当然。

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

IE:

dict.Values.SelectMany( v => v).Count(  v => v == "specific value" );
于 2013-03-25T14:38:23.380 回答
5

我会使用这个版本:

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

[编辑] 好的,这里有一些比较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);
            }
        }
    }
}
于 2013-03-25T14:43:34.280 回答