Var in LINQ


What is Var

Var is data type in C# which holds the anonymous data. When you do not know the return type we can hold data in var. The declaration and definition of var type will be declare in the same line.

Example of Var

 Var x;
 X=10;
 
That will be wrong syntax in case of var. Following is the correct syntax of Var
Var x=10;

Grouping in LINQ

Let’s perform the grouping the last example according to the course then we will use the code as follows with var data type:-
  
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //creat list and add some object
        List<viastudy> data = new List<viastudy>() {
            new viastudy{ stu_id=1, stu_name="durgesh", stu_course="asp.net"},
            new viastudy{ stu_id=2, stu_name="shallu", stu_course="Web Designing"},
            new viastudy{ stu_id=3, stu_name="duggu", stu_course="asp.net"},
            new viastudy{ stu_id=4, stu_name="bittu", stu_course="oracle"}

        };

        //take the var data type
        var res = from final_Res in data
                  group final_Res by final_Res.stu_course;     
        foreach (var course in res)
        {
            //preint the key on which we grouped data
            Response.Write("<html></br></br></html>"+course.Key + "<html></br></br></html>");

            foreach (var stu_data in course)
            {
                //show data
                Response.Write("Student Id=" + stu_data.stu_id + " Student Name=" + stu_data.stu_name + " Student Course=" + stu_data.stu_course+"<html></br></html>");
            }
        }

    }
}    
The output of this code is as follows:-

No comments:

Post a Comment