我试图获得每个 studentId 相同天数的总数。我已将日期时间转换为星期几(整数)。GetAllInfo 从其他类接收所有需要的数据。然后 GetTimeExercises 使用此数据。
列表练习中的数据示例: (291, 5) (301, 5) (291, 5)
291 是学生证,5 是星期几。
现在我想计算列表中的所有重复值并将总数添加到列表或字典中。通缉结果:学生证+总天数
例如: (291, 5) (301, 5) (291, 5) 应该给 (291, 2) (301, 5)
private List<Tuple<int, int>> ExcercisesWithTime = new List<Tuple<int, int>>();
public void GetAllTimeWithExercises()
{
GetAllInfo();
GetTimeExercise(AllStudentInfo);
}
private void GetTimeExercise(List<IctLabTable> studentInfo)
{
foreach (var item in studentInfo)
{
ExcercisesWithTime.Add(new Tuple<int, int>(item.StudentId, ConvertDayOfWeek(item.CreatedAt)));
}
}
private int ConvertDayOfWeek(DateTime dateValue)
{
int dayOfWeek = (int) dateValue.DayOfWeek;
return dayOfWeek;
}
我尝试了不同的东西,但没有成功。我试图通过创建字典来解决它:
private Dictionary<int, Tuple<int, int>> StudentDayTotalExercises = new Dictionary<int, Tuple<int, int>>();
//// Studentid + day (Example: 291 + 5)
private void CountSameDays(List<Tuple<int, int>> xList)
{
foreach (var item in xList)
{
var TotalDays = 1;
if (!StudentDayTotalExercises.ContainsKey(item.Item1))
{
var TupleStudentDays= new Tuple<int, int>(item.Item2, TotalDays );
StudentDayTotalExercises.Add(item.Item1, TupleStudentDays);
}
else
{
Here I wanted to increment the value if the key existed. But without success.
//StudentDayTotalExercises[item.Item1, ]++;
}
}
}
只需按 分组Tuple
并计算出现次数:
List<Tuple<int, int>> excercisesWithTime = new List<Tuple<int, int>>
{
Tuple.Create(291, 5),
Tuple.Create(301, 5),
Tuple.Create(291, 5)
};
// method syntax
var result = excercisesWithTime.GroupBy(key => key, item => 1)
.Select(group => new {
group.Key,
Duplicates = group.Count()
});
//query syntax
var result = from item in excercisesWithTime
group 1 by item into g
select new {
g.Key,
Duplicates = g.Count()
};
我建议您创建一个带有属性的适当类,而不是使用Tuple
s。用法更清晰,您无需记住在每个文件ItemX
中放置了什么。
如果您正在使用 C# 7.0,请查看其有关元组的功能
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句