LINQ Distinct Count возвращает 1 - PullRequest
0 голосов
/ 30 мая 2018

Я создаю делегат 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;
        };

1 Ответ

0 голосов
/ 30 мая 2018

Вы неправильно понимаете, что делает Distinct.У вас есть два идентичных элемента, 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());   
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...