2011-05-19 71 views
4

有没有简单的方法来获得特定字典键值的值?C#字典ArrayList计数

static void Main() 
{ 
    Dictionary<string, ArrayList> SpecTimes = new Dictionary<string, ArrayList>; 
    ArrayList times = new ArrayList(); 
    string count = ""; 

    times.Add = "000.00.00"; 
    times.Add = "000.00.00"; 
    times.Add = "000.00.00"; 

    string spec = "A101"; 

    SpecTimes.Add(spec,times); 

    count = SpecTimes[spec].values.count; 
} 
+1

这看起来像一半C#和一半......我不知道。 – BoltClock 2011-05-19 15:07:26

+0

不要使用'ArrayList's。相反,使用'List ' – SLaks 2011-05-19 15:07:51

+0

为什么混合泛型集合和非泛型集合?而不是在方法调用中使用括号?请显示*真实*代码。 – 2011-05-19 15:08:17

回答

4

我还没有测试过它,但是这应该接近你所需要的。

static void Main() 
{ 
    Dictionary<string, List<string>> SpecTimes = new Dictionary<string, List<string>>(); 
    List<string> times = new List<string>(); 
    int count = 0; 

    times.Add = "000.00.00"; 
    times.Add = "000.00.00"; 
    times.Add = "000.00.00"; 

    string spec = "A101"; 

    SpecTimes.Add(spec,times); 

    // check to make sure the key exists, otherwise you'll get an exception. 
    if(SpecTimes.ContainsKey(spec)) 
    { 
     count = SpecTimes[spec].Count; 
    } 
} 
2

您的代码不会原样编译,你不应该使用ArrayList的,而是List<T>(如SLaks指出。)话虽这么说,List<T>Count属性,因此SpecTime[key].Count应工作得很好(假设密钥实际上在字典中)。

+0

我知道你的意思是说'Dictionary '具有'Count'属性。 – 2011-05-19 15:31:44

+0

@Rick它确实,但为什么这就是我的意思? – dlev 2011-05-19 15:33:15

+0

读得太快。 Mea culpa。 ('SpecTime.Count'与'SpecTime [key] .Count') – 2011-05-19 15:37:31

1

如果你使用.NET 3.5以上,使用Linq此:

var count = (from s in SpecTimes where SpecTimes.Key == <keyword> select s).Count(); 

反正大家都建议,你应该选择List<string>超过ArrayList

3

有一些错误在你的代码中,所以它不会编译。你应该这样改变它:

static void Main() 
{ 
    IDictionary<string, IList<string>> specTimes = new Dictionary<string, IList<string>>(); 
    IList<string> times = new List<string>(); 

    times.Add("000.00.00"); 
    times.Add("000.00.00"); 
    times.Add("000.00.00"); 

    string spec = "A101"; 
    specTimes.Add(spec, times); 

    int count = specTimes[spec].Count; 
} 

既然你已经得到了出现的次数,那究竟是什么问题呢?

1

如果使用.NET 3.5,则可以使用Linq进行筛选和计数。但是如果可能的话避免使用ArrayList,并使用泛型。

static void Main(string[] args) 
    { 
     Dictionary<string, List<string>> SpecTimes = new Dictionary<string, List<string>>(); 
     List<string> times = new List<string>(); 
     int count; 

     times.Add("000.00.00"); 
     times.Add("000.00.00"); 
     times.Add("000.00.00"); 
     times.Add("000.00.01"); 

     string spec = "A101"; 

     SpecTimes.Add(spec,times); 

     // gives 4 
     count = SpecTimes[spec].Count; 

     // gives 3 
     count = (from i in SpecTimes[spec] where i == "000.00.00" select i).Count(); 

     // gives 1 
     count = (from i in SpecTimes[spec] where i == "000.00.01" select i).Count(); 
    }