开发者

C# Dictionary ArrayList Count

Is there an easy way to get a count on the values of a specific dictionarys keys values?

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;
}


I haven't tested it, but this should be close to what you need.

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;
  }
}


There are some errors in your code, so it would not compile anyway. You should change it like this:

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;
}

Since you already get the number of occurences, what is the problem anyway?


Your code isn't going to compile as is, and you shouldn't be using ArrayList, but rather List<T> (as SLaks pointed out.) That being said, List<T> has a Count property, so SpecTime[key].Count should work just fine (assuming key is actually in the dictionary.)


If you're using .NET 3.5 and above, use Linq for this:

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

anyway, as everyone suggested, you should choose List<string> over ArrayList


If using .NET 3.5 you can use Linq to filter and count. However avoid ArrayList if possible, and use generics.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜