Search code examples
c#linqlinq-to-sql

Count and compare boolean values using Linq


I am trying to count the false count per item in attentdanceList from the code below. My goal is to only pick those items whose false count is greater than or equal to 2.

False count: the number of times an item has the attent.present as false.

var attentdanceList = 
    from attent in attentdance
    orderby attent.UpdatedOn descending
    where !attent.Present && attent.UpdatedOn >= DateTime.Now.AddDays(-3)
    select new AttentdanceResponse
    {
        Id = attent.RowKey,
        SchoolId = attent.PartitionKey,
        StudentId = attent.StudentId,
        ClassRoomId = attent.ClassRoomId,
        TeacherId = attent.TeacherId,
        Latitude = attent.Latitude,
        Longitude = attent.Longitude,
        Present = attent.Present,
        Timestamp = (DateTime)attent.UpdatedOn
    };

The code above gives the following output: enter image description here

Goal: to select only those items whose false count is >= 2.


Solution

  • You should use a GroupBy to group the students together, and then count the present-boolean.

    I created a snippet for you: https://dotnetfiddle.net/K9hFVo

            // Student collection
            IList<Student> studentList = new List<Student>()
            {
                new Student() { StudentID = 1, StudentName = "John", Present = true },
                new Student() { StudentID = 2, StudentName = "Ram", Present = false },
                new Student() { StudentID = 1, StudentName = "John", Present = false },
                new Student() { StudentID = 2, StudentName = "Ram", Present = true },
                new Student() { StudentID = 1, StudentName = "John", Present = false }
            };
    
            // LINQ Query Syntax to find out teenager students
            var groups = studentList.GroupBy(x => x.StudentID).Where(x => x.Count(y => !y.Present) >= 2);
    
            foreach (var studentGrouping in groups)
            {
                Console.WriteLine($"studentid: " + studentGrouping.Key);
            }