[英]Count value at specific dictionary key C#
我必须计算特定键处字典的值。 我的代码是:
foreach (CurrentCluster curCluster in curClusters){
twObjClus.WriteLine("Cluster_ID: {0} - Cluster_Size: {1} \n",
curCluster.GetClusterID(), curCluster.GetClusterSize());
twObjClus.WriteLine("------------------------------------------------------------");
foreach (EvoObject eEvoObject in curCluster.GetClusterObjects()){
Author eAuthor = (Author)eEvoObject.GetOriginalObject();
twObjClus.WriteLine("\n");
twObjClus.WriteLine(@"Author_ID: {0}, Author_Name: {1} ",
eAuthor.AuthorID, eAuthor.AuthorName);
twObjClus.WriteLine("----------------------------------------------------------");
Dictionary<int, Tuple<int, int>> tPapers =
eAuthor.GetPapersBetweenYears(year, year + 1);
List<int> tCoAuthors =
eAuthor.GetCoAuthorsBetweenYears(year, year + 1);
List<int> tVenues = eAuthor.GetVenuesBetweenYears(year, year + 1);
foreach (var kvpaper in tPapers){
// Key is Paper_ID, Item1 is Paper_Category, Item2 is Year
twObjClus.WriteLine("PaperID: {0}, PaperCategory: {1}, Year: {2}",
kvpaper.Key, kvpaper.Value.Item1, kvpaper.Value.Item2);
}
foreach (var kvCoAuthor in tCoAuthors){
twObjClus.WriteLine("CoAuthorID: {0}", kvCoAuthor);
}
foreach (var kvVenue in tVenues){
twObjClus.WriteLine("VenueID: {0}", kvVenue);
}
}
twObjClus.WriteLine("\n\n");
}
twObjClus.Flush(); twObjClus.Close();
现在,我想计算Paper_Category
每个不同值,即Dictionary
Paper_Category
Tuple
Item1
。
次要细节
这实际上是我要从数据中获取结果的聚类。 由于每个群集将具有与某些对象关联的Paper_Category
数量。 我想要的是对每个类别进行计数,并将该群集存储为单个类别,即计数最高的类别。
如果eAuthor
是一个列表,并且我必须检查所有eAuthor
最高的Paper_Category
计数,并且每个eAuthor
也可能包含几个Paper_Category
,那么该如何计数?
如何计算Paper_Category
每个值的Paper_Category
并将其写为文本?
var categoryGroups = tPapers.Values.GroupBy(t => t.Item1);
foreach(var g in categoryGroups)
Console.WriteLine("Category:{0} Count:{1}", g.Key, g.Count());
如何选择或存储计数最高的类别(在变量中)?
var highestCount = categoryGroups.OrderByDescending(g => g.Count())
.Select(g => new { Category = g.Key, Count = g.Count() })
.First();
Console.WriteLine("Category:{0} Count:{1}", highestCount.Category, highestCount.Count);
由于您想获取eAuthor
所有作者的论文类别计数,并且这似乎是您的课程,因此请使用SelectMany
:
var categoryGroups = eAuthor
.SelectMany(a => a._Papers.Select(p => p._PaperCategory))
.GroupBy(pc => pc);
// rest is same
正如您在评论中提到的,使用linq来获得最高收益:
int? highestCat = tPapers.Values.GroupBy(p => p.Item1)
.OrderByDescending(x => x.Count())
.FirstOrDefault()?.Key;
Console.WriteLine($"Highest Paper_Category is: { highestCat }");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.