如何获取字典中列表的数量

时间:2019-06-13 15:47:55

标签: c# list dictionary count

我有一个列表字典,我想分别计算每个列表中的项目数。例如

cnlp_get_entity(obj) %>%
  filter(entity_type == "PERSON") %>%
  group_by(entity) %>%
  summarise(count = n()) %>%
  top_n(n = 50) %>%
  arrange(desc(count)) %>%
  use_series(entity)

代码应该说list1包含2次,list2包含3个项目,依此类推

向我显示了数字列表,因此在这种情况下3并不是我所需要的: dic.values.count

还给出了列表中总数的总和,因此在这种情况下为8: dic.values.sum(x => x.count)

2 个答案:

答案 0 :(得分:1)

String report = String.Join(
    Environment.NewLine, 
    dict.Select( kvp => "List '" + kvp.Key + " has " + kvp.Value.Count.ToString("N0") + " items." )
);

或者:

String report = String.Join(
    Environment.NewLine, 
    dict.Select( kvp => $"List '{kvp.Key}' has {kvp.Value.Count:N0} items." )
);

答案 1 :(得分:0)

以下代码可以完成工作:

// dict is of type Dictionary<string, List<string>>
foreach(KeyValuePair<string, List<string>> entry in dict)
{
    Console.WriteLine("List " + entry.Key + " contains " + entry.Value.Count() + " items");
}