我必须在特定键上计算字典的值。我的代码是:
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
中Item1
的每个不同值,即Tuple
中Dictionary
的{{1}}。
次要细节
这实际上是我从我的数据中获取结果所做的聚类。因为每个群集将具有与某些对象相关联的Paper_Category
个数量。我想要的是计算每个类别并将该群集存储为单个类别,即具有最高计数的类别。
如果eAuthor
是一个列表,我必须在所有Paper_Category
中检查最高eAuthor
次,并且每个eAuthor
可能包含多个Paper_Category
个还有,那怎么算?
如何计算Paper_Category
的每个值的存在并将其写为文本?
答案 0 :(得分:5)
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
和this中的所有作者中获取纸张类别计数似乎是您的班级,请使用SelectMany
:
var categoryGroups = eAuthor
.SelectMany(a => a._Papers.Select(p => p._PaperCategory))
.GroupBy(pc => pc);
// rest is same
答案 1 :(得分:1)
使用linq获得最高评价:
int? highestCat = tPapers.Values.GroupBy(p => p.Item1)
.OrderByDescending(x => x.Count())
.FirstOrDefault()?.Key;
Console.WriteLine($"Highest Paper_Category is: { highestCat }");