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:
Goal: to select only those items whose false count is >= 2.
CodePudding user response:
I may have misunderstood the question, but if you're trying to count how many items have Present
as False, here is how you do it:
You can use the Method syntax of Linq instead of the SQL syntax:
var failCount = 0;
var attendanceList = attendance
.OrderByDescending(attent => attent.UpdatedOn)
.Where(attent =>
{
if(!attent.Present)
failCount ;
return !attent.Present && attent.UpdatedOn >= DateTime.Now.AddDays(-3));
})
.Select(attent => 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
})
.ToArray();
Because of the way Linq does these things (i.e. the IEnumerable isn't actually processed until it is requested in the code), I think you would need to call ToArray
(or ToList
depending on what you need) at the end as well. Not 100% positive if it will affect the failCount
, but it won't hurt to be sure by calling ToArray
. ToArray
forces the Linq statement to be executed by returning an array.
CodePudding user response:
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);
}