Determine Ratio using LINQ

Let us see an example where you need to determine the Pass/Fail Ratio of students in a school. We will use LINQ to do so:

C#


List<Student> stuList = new List<Student>();


stuList.Add(new Student() { ID = 1, FName = "Shakiy",Result = 'P' });


stuList.Add(new Student() { ID = 2, FName = "Mary", Result = 'P' });


stuList.Add(new Student() { ID = 3, FName = "Bill", Result = 'F' });


stuList.Add(new Student() { ID = 4, FName = "Samantha", Result = 'F' });


stuList.Add(new Student() { ID = 5, FName = "Mary", Result = 'P' });


 


// Sex Ratio


var ratioSex = stuList.GroupBy(ra => ra.Result)


  .Select(stu => new


  {             


      Rato = (stu.Count() * 100) / stuList.Count


  });


 


foreach (var ratio in ratioSex)


{


    // Print ratio.Res and ratio.Rato


}




VB.NET


        Dim stuList As New List(Of Student)()


        stuList.Add(New Student() With {.ID = 1, .FName = "Shakiy", .Result = "P"c})


        stuList.Add(New Student() With {.ID = 2, .FName = "Mary", .Result = "P"c})


        stuList.Add(New Student() With {.ID = 3, .FName = "Bill", .Result = "F"c})


        stuList.Add(New Student() With {.ID = 4, .FName = "Samantha", .Result = "F"c})


        stuList.Add(New Student() With {.ID = 5, .FName = "Mary", .Result = "P"c})


 


        ' Sex Ratio


        Dim ratioSex = stuList.GroupBy(Function(ra) ra.Result) _


        .Select(Function(stu) New With {Key .Rato = (stu.Count() * 100) / stuList.Count})


 


        For Each ratio In ratioSex


            ' Print ratio.Res and ratio.Rato


        Next ratio


No comments:

Post a Comment