LINQ to Array


Query writing in LINQ

LINQ allows us to write query against all data whether it comes from array, database, XML etc. This is the best feature of LINQ.
Before going deep into LINQ lets run some basic queries in LINQ using arrays and try to understand the syntax of LINQ
The namespace which is used for these queries is as follows:-
using System.Linq;

Example of LINQ Queries

Let’s take the string array which contains the name of student as follows:-

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //declare the array
        string[] techaltum_student = new string[] { "durgesh", "duggu", "shallu", "munna" };
       
        //quey using LINQ syntax
        IEnumerable<string> str_res = from res in viastudy_student
                                      select res;

        //access the element and print in the screen
        foreach (string final_res in str_res)
        {
            //show data with some spaces
            Response.Write(final_res+"   ");
       
        }
    }
}
 
  
 
The output of this code as follows:-

Where Clause in LINQ

We can also filter data using where clause. Some queries and answer as follows:- Show the names which length are 4 then we will write the query as follows:-
  
IEnumerable<string> str_res = from res in viastudy_student
           where res.Length==4
           select res;
 
  
Show the name which has the word “sh”


  
  IEnumerable<string> str_res = from res in viastudy_student
           where res.Contains("na")
           select res;

  
  

order by in linq Query

If we want to sort the data then we use the order by in the query as follows:-
  
  IEnumerable<string> str_res = from res in viastudy_student
             where res.Contains("sh")
           orderby res
           select res;

  
By default it will sort in ascending order.
If we want to sort in descending order then we will write the query as follows:-

IEnumerable<string> str_res = from res in viastudy_student where res.Contains("sh") orderby res descending select res;

No comments:

Post a Comment