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




Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: