如何在包含lambda表达式的字符串列表的字典中获取值的实例数?
private Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
下面需要改进以消除错误;基本上无法将字符串与字符串列表进行比较。
int count = dict.Values.Count(v => v == "specific value");
答案 0 :(得分:5)
使用linq?肯定的。
dict.Values.SelectMany( v => v).Where( v => v == "specific value").Count();
即:
dict.Values.SelectMany( v => v).Count( v => v == "specific value" );
答案 1 :(得分: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加倍,这导致总共四倍的字符串数。
两种算法&#39;时间增加了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);
}
}
}
}