C# C.如何创建具有新值且与原始列表大小不同的列表
例如,主要数据是 主题作者问题 : 运动泰勒“问题” 历史泰勒的问题 运动泰勒“问题” 我需要计算每个主题有多少个问题,并显示答案,我需要创建另一个列表,其中只包含我计算的主题和数量。 所以它应该是这样的: 运动2 历史1 数一数有多少问题,我只是C# C.如何创建具有新值且与原始列表大小不同的列表,c#,list,arraylist,C#,List,Arraylist,例如,主要数据是 主题作者问题 : 运动泰勒“问题” 历史泰勒的问题 运动泰勒“问题” 我需要计算每个主题有多少个问题,并显示答案,我需要创建另一个列表,其中只包含我计算的主题和数量。 所以它应该是这样的: 运动2 历史1 数一数有多少问题,我只是 static void Method(List<Class> list) { int sport = 0; int history = 0; for (int i = 0; i &l
static void Method(List<Class> list)
{
int sport = 0;
int history = 0;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Theme == "History")
{
history++;
}
else if (list[i].Theme == "Sport")
{
sport++;
}}
所以我想知道如何通过列表来显示它,你可以用字典来实现!只需查看以下代码:
static void Theme(List<Class> list) {
var dict = new Dictionary<string, int>();
for (var current in list) {
if (dict.ContainsKey(current.Theme) {
dict[current.Theme]++;
} else {
dict[current.Theme] = 1;
}
}
}
之后,你就可以在dict中记下你的计数了。只需要用dict[历史]来记就可以了。听起来你只是想要主题和计数?您可以按主题对项目进行分组,并计算每组中的项目数:
var sportsAndCounts = list
.GroupBy(x => x.Theme)
.Select(x => $"{x.Key} {x.Count()}");
这将创建您正在描述的字符串,但您可以将分组投影到您需要的任何对象。使用实体框架。。你可以做到这一点
var query = list.GroupBy(p => p.Theme)
.Select(g => new { Sport = g.Key, Count = g.Count() });
在var查询中,你应该拥有你假装的东西
没有测试代码
List<Question> QuestionList = new List<Question>
{
new Question{ Theme = "Sport", Author = "Tyler", T = "Question", },
new Question{ Theme = "History", Author = "Tyler", T = "Question", },
new Question{ Theme = "Sport", Author = "Tyler", T = "Question", },
};
var HistoryCount = QuestionList.Count(x => x.Theme == "History");
var SportCount = QuestionList.Count(x => x.Theme == "Sport");
历史计数为2,
SportCount将为1
这将要求您参考System.Linq 最简单的方法是使用Linq和分组方法,如下所示
var query = from item in list
group item by item.Theme into group
select new { Question = group.Key, Count = group.Count()};
foreach(var item in query){
Console.WriteLine("{0} {1}", item.Question, item.Count);
}
Dictionary<string, int> themes = new Dictionary<string, int>();
但您也可以使用字典存储每个主题及其计数:
Dictionary<string, int> themes = new Dictionary<string, int>();
for (int i = 0; i < list.Count; i++)
{
if(themes.ContainsKey(list[i].Theme))
themes[this[i].Theme]++;
else
themes[this[i].Theme = 1;
}
foreach(var keyValuePair in themes.OrderByDescending(x => x.Value).ThenBy(x => x.Key)){
Console.WriteLine("{0} {1}", keyValuePair.Key, keyValuePair.Value);
}
请你解释一下“如何通过列表显示”是什么意思?我的意思是,在我数完问题之后,我需要整理列表。所以我不知道怎样才能整理出这个列表,若我并没有使用列表数组的话,它对我的字典很有用,谢谢。但是我怎么才能把我得到的结果整理出来呢。例如,按计数的降序排列,如果计数等于字母顺序,因为若我得到了列表数组,我只需在类中添加IComparable,然后再添加List.Sort;但是这里我有两个独立的值,我编辑了答案,所以字典是按计数排序的,然后是按主题排序的。