我在我的方法中创建一个委托Func,以检查 schedualCode 是否适合列表中的某个位置,其中限制为3。 我想在列表中计算schedualCode的不同值。我的问题是schedualCodeCount返回1.它应该返回2。 这是我的代码
Func<string, bool> CheckTimeLimit = delegate (string schedualCode)
{
// check enrolled period count (where limit is 3)
//int periodCount = currentEnrollments.GroupBy(t => t.Times)
//.Select(t => t.Key.Select(key => key.PeriodCode == time.PeriodCode).Distinct()).Count();
var allTimes = currentEnrollments.SelectMany(key => key.Times).ToList();
List<string> schedualCodes = allTimes.Where(key => key.SchedualCode == schedualCode && key.ViewOnSchedual)
.Select(key => key.SchedualCode).ToList();
//schedualCodes List returns a list of count = 2 , and 2 strings exactly the same of value = "A1"
// Getting the distinct count of "A1"
int schedualCodeCount = schedualCodes.Distinct().Count();
// schedualCodeCount gets the value = 1, where it should be 2
// time fits if true
return schedualCodeCount < 3;
};
答案 0 :(得分:1)
你误解了Distinct的作用。你有两个相同的项目,区别将删除你留下的重复项1.您可能想要做的是分组,然后得到每个组的计数。
例如:
var list = new List<string>() { "A1", "A1" };
Console.WriteLine(list.Count); // 2, obviously
var distinct = list.Distinct(); // select only the *distinct* values
Console.WriteLine(distinct.Count()); // 1 - because there is only 1 distinct value
var groups = list.GroupBy(s => s); // group your list (there will only be one
// in this case)
foreach (var g in groups) // for each group
{
// Display the number of items with the same key
Console.WriteLine(g.Key + ":" + g.Count());
}