vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Saturday, February 9, 2013

How to use LINQ in List collection



Linq is stands for Language integrated query, its Microsoft DOTNET framework model, start from the framework 3.5
Linq enables you to query and manipulate data independently of data source. Data source may be the sql or dataset or XML
Linq encapsulates generics and it’s provided full safety and makes code more readable.
Linq supports the following providers,

  •  Linq to SQL
  • Linq to dataset
  • Linq to objects
  • Linq to XML

LINQ to objects:

By using this LINQ we must add the namespace using System.Linq;
1) First we need to create Generics List with set of strings, from the string we need to find the string start with letter of “A” using LINQ

List<string> lststr = new List<string>();
        lst.Add("vijay");
        lst.Add("anand");
        lst.Add("arun");
        lst.Add("ahamed");
        lst.Add("shahul");

        var r= from element in lst where element.StartsWith ("a")    select element;

        foreach (var r1 in r)
        {
            lststr.Add(r1.ToString());
            Response.Write("</br>" + r1);
        }


Output:
anand
arun
ahamed




2) In this process we create list of string array, from this array we must find the first array of the string using LINQ

   List<string[]> lst1 = new List<string[]>();

        string[] a = { "4", "8", "9" };
        string[] b = { "1", "3", "7" };
        string[] c = { "14", "18", "19" };
        string[] d = { "24", "28", "29" };
        lst1.Add(a);
        lst1.Add(b);
        lst1.Add(c);
        lst1.Add(d);

       var coll = from int1 in lst1 where int1[0].Equals("1") select int1;

        foreach (var r2 in coll)
        {
            Response.Write("</br>" + r2[0] + r2[1] + r2[2]);
        }

Output:
137

3) We create integer array then we start the array using LINQ

int[] a1 = { 2, 1, 4, 56 };

       
        var col2 = from int2 in a1 orderby int2 descending select int2;

        foreach (var r3 in col2)
        {
            Response.Write("</br>" + r3);
        }

Output:
56
4
2

I hope you have understood how to use LINQ in generics list……….

0 comments:

Post a Comment