如何在包含带有lambda表达式的字符串列表的字典中获取值的实例数?
private Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();下面需要改进以消除错误;基本上不能将字符串与字符串列表进行比较。
int count = dict.Values.Count(v => v == "specific value");发布于 2013-03-25 22:43:34
我会使用这个版本:
int count = dict.Count(kvp => kvp.Value.Contains("specific value"));编辑Ok,这里是比较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.9109115n1 = 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);
}
}
}
}https://stackoverflow.com/questions/15617607
复制相似问题