2013-03-25 66 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