[英]C#: Count distinct values in list of tuples
我正在嘗試獲取每個studentId的同一天總數。 我已經將日期時間轉換為星期幾(整數)。 GetAllInfo從另一個類接收所有需要的數據。 然后,GetTimeExercises使用此數據。
清單ExercisesWithTime中的數據示例:(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
。 使用更加清晰,您無需記住放置在每個ItemX
的內容。
如果您使用的是C#7.0,請參見其有關元組的功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.