In this example, I will show how to average row value using LINQ in C# Windows Form.
I have shown a very simple example to average total value from list. I have created a two classes one student and another student Mark to provide temporary data to grid view .In this case student and student-Mark class has a parent and child class relationship to each other. Hear I will find average number each student using LINQ Average() Method.
Output:
Student.cs
1 2 3 4 5 6 7 8 | public class Student { public int ID { get; set; } public string StduentName { get; set; } } |
StudentMark.cs
1 2 3 4 5 6 7 8 9 | public class StudentMark { public int StduentID { get; set; } public string StduentName { get; set; } public string Subject { get; set; } public decimal ObtainNumber { get; set; } } |
Form.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); var data = from s in GetStudentList() join m in GetStudentMarkList() on s.ID equals m.StduentID group new { m, s } by new { s.StduentName } into g select new { StudentName = g.Key.StduentName, AverageNumber = Math.Round(g.Average(i => i.m.ObtainNumber), 2) }; dataGridView1.DataSource = data.ToList(); } private List<Student> GetStudentList() { List<Student> StudentList = new List<Student> { new Student{ID=1, StduentName="Timon Cooker"}, new Student{ID=2, StduentName="Abrahim Collins"}, new Student{ID=3, StduentName="Britney Bluehouse"}, }; return StudentList; } private List<StudentMark> GetStudentMarkList() { List<StudentMark> StudentMarkStudentMarks = new List<StudentMark>{ new StudentMark{StduentID=1, Subject="English", ObtainNumber =88}, new StudentMark{StduentID=1, Subject="Math", ObtainNumber =95}, new StudentMark{StduentID=1, Subject="Accounting", ObtainNumber =65}, new StudentMark{StduentID=2, Subject="English" , ObtainNumber =75}, new StudentMark{StduentID=2, Subject="Math" , ObtainNumber =95}, new StudentMark{StduentID=2, Subject="Accounting" , ObtainNumber =55}, new StudentMark{StduentID=3, Subject="English" , ObtainNumber =88}, new StudentMark{StduentID=3, Subject="Math" , ObtainNumber =85}, new StudentMark{StduentID=3, Subject="Accounting" , ObtainNumber =79} }; return StudentMarkStudentMarks; } } } |