2013-03-25 51 views
0

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

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

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

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

像错误说你是比较列表字符串。 – 2013-03-25 14:37:38

回答

5

我会用这个版本:

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

[编辑]好吧,这里的一些结果比较Contains()方法与SelectMany()方法(86发行版):

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.
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); 
      } 
     } 
    } 
} 
+0

这也将是一个O(n^2)解决方案,但它是正确的。 – 2013-03-25 14:45:45

+0

我只是添加一些时间测试。 :) – 2013-03-25 14:55:14

+0

你可能是对的,实际上这很有趣。 – 2013-03-25 14:55:52

5

using linq?当然。

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

即:

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

我不相信这是O(n)... – 2013-03-25 14:53:32

+0

我不相信这是实际上,即时运行一些测试,结果是有趣的。我会假设SelectMany做了1次传递,并且Count做了另一次传递,使它仍然是线性的O(2n)... – 2013-03-25 14:55:36

+0

是的,O(2n)== O(N)正确。 – 2013-03-25 15:03:06