Linq in C# Programming

Before using LINQ in C#, please read my earlier blog to get some basic idea about what is LINQ?

LINQ can be used in C# in different ways :

One way is to use with Lambda Expression
Another way is to use Anonymous function


Below code will return string of length less than 5.

string[] countryArr = { "India""USA""UK""China""Japan""Germany""Australia" };
            var data = countryArr.Where(a => a.Length < 5).Select(a => a);
            foreach (string sdata in data)
            {
                Console.WriteLine(sdata);

            }

O/P : - USA, UK

Above code can be written using Anonymous function

Write below function

Func<stringbool> wh = delegate (string s)
        { return s.Length < 5; };
        Func<stringstring> sel = delegate (string s)
        { return s; };

Below function to implement the LINQ

private void PrintData()
        {
            string[] countryArr = { "India""USA""UK""China""Japan""Germany""Australia" };
            var data = countryArr.Where(wh).Select(sel);
            foreach (string sdata in data)
            {
                Console.WriteLine(sdata);
            }
        }

Below Code to select only integer from given array

object[] arData = { "test", 1, 10, "my name", 12, "laptop""Mouse", 20, 22, 25, 50, "LINQ Program" };
            var aa = arData.OfType<int>();

            foreach (int s in aa)
            {
                Console.WriteLine(s);
            }

Below code to select integer data less than 25 and order by clause from array.

object[] arData = { "test", 1, 10, "my name", 12, "laptop""Mouse", 20, 22, 25, 50, "LINQ Program" };
            var aa = arData.OfType<int>()
                .OrderBy(a => a)
                .Where(a => a < 25)
                .Select(a => a);

            foreach (int s in aa)
            {
                Console.WriteLine(s);
            }
Join in LINQ

There are 2 arrays, below code join 2 arrays to select matching data from 2nd array.

object[] countryMaster = {"INDIA","USA""UK","AUSTRALIA","JAPAN"};
object[] country = { "INDIA","USA","JAPAN"};

            var joinData = countryMaster.OfType<string>()
                .Join(country.OfType<string>(),
                p => p, t => t,
                (p, t) => p);

            foreach (var s in joinData)
            {
                Console.WriteLine(s);
            }

Popular posts from this blog

Calling REST APi from server side code - C#

All about SharePoint 2010 Content Type Hub

Calling ASP.Net WebMethod using jQuery AJAX