Monday, 18 August 2014

Write a Program To find out the highest marks of all students whose scores are high in each departments using LINQ

Here i would like to explore the implementation of LINQ.
Consider a List which contains Sid, Marks,SName, Dept of student.







Program:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<MyClass> o = new List<MyClass>();
            o.Add(new MyClass { Sid = 1, SName = "ABC", Dept = "CSE", Marks = 90 });
            o.Add(new MyClass { Sid = 2, SName = "DEF", Dept = "CSE", Marks = 92 });
            o.Add(new MyClass { Sid = 3, SName = "GHI", Dept = "IT", Marks = 68 });
            o.Add(new MyClass { Sid = 4, SName = "JKL", Dept = "IT", Marks = 70 });
            o.Add(new MyClass { Sid = 5, SName = "MNO", Dept = "CSE", Marks = 99 });
            o.Add(new MyClass { Sid = 6, SName = "PQR", Dept = "CSE", Marks = 99 });
            o.Add(new MyClass { Sid = 7, SName = "STU", Dept = "IT", Marks = 96 });
            int CSEMARKS = (from p in o where p.Dept == "CSE" select p.Marks).Max();            
            int ITMarks = (from p in o where p.Dept == "IT" select p.Marks).Max();           
            List<MyClass> tempCse = new List<MyClass>();
            List<MyClass> tempIT = new List<MyClass>();
            int sno = 1;
            int itsno = 1;
            o.ToList().ForEach(p =>
                {                   
                    if (p.Dept == "CSE" && p.Marks == CSEMARKS)
                    {                       
                        p.Sid = sno;
                        tempCse.Add(p);
                        sno++;  
                    }
                    if (p.Dept == "IT" && p.Marks == ITMarks)
                    {
                        p.Sid = itsno;
                        tempIT.Add(p);
                        sno++;
                    }
                });
            Console.WriteLine("Students Whose Scores is hogh in CSE Branch is:");                    
            if (tempCse != null && tempCse.Count > 0)
            {
                foreach (var q in tempCse)
                {  
                    Console.WriteLine(q.Sid+"\t"+q.SName+"\t"+q.Dept+"\t"+q.Marks);
                }
            }
            Console.WriteLine("Students Whose Scores is hogh in IT Branch is:");
            if (tempIT != null && tempIT.Count > 0)
            {
                foreach (var q in tempIT)
                {                                         
                    Console.WriteLine(q.Sid + "\t" + q.SName + "\t" + q.Dept + "\t" + q.Marks);
                }
            }
            Console.ReadLine();
        }
    }
    class MyClass
    {
        public int Sid, Marks;
        public string SName, Dept;
    }
}






Output:
LINQ EXAMPLE
LINQ EXAMPLE

No comments :

Post a Comment