Saturday, April 24, 2021

LINQ let clause Example

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

namespace Console_LINQ_let_clause
{
    class LinqClauses
    {
        public void LinqExample01()
        {
            Console.WriteLine("\nLinqExample01");
            List<string> fullnames = new List<string>()
            {
                "Ajeet Kumar", "Rajeev Gupta", "Mohit Sharma", "Vinay Dubey",
                "Amit Gupta", "Mira Gupta", "Arvind Sharma", "Sagar Gupta"
            };
            //find all first names using LINQ
            var queryvar = from fullname in fullnames
                          select fullname.Split(' ')[0];
            //execute queryvar
            foreach (var item in queryvar)
            {
                Console.WriteLine(item);
            }

        }

        public void LinqExample02()
        {
            Console.WriteLine("\nLinqExample02");
            List<string> fullnames = new List<string>()
            {
                "Arjun Kumar", "Krishna Gupta", "Maya Sharma", "Bhim Dubey",
                "Nakul Gupta", "Radha Gupta", "Arvind Sharma", "Sagar Gupta"
            };
            //find all first names using LINQ
            /*
             * let clause is used to store the result of an expression 
             * let variable is new range variable
             * fullname is range variable which is replaced by firstname
             */
            var firstnames = from fullname in fullnames
                           let firstname = fullname.Split(' ')[0]
                           select firstname;
            //execute firstnames
            foreach (var first in firstnames)
            {
                Console.WriteLine(first);
            }

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LinqClauses c = new LinqClauses();
            c.LinqExample01();
            c.LinqExample02();
            Console.ReadKey();
        }
    }
}

OUTPUT


LinqExample01
Ajeet
Rajeev
Mohit
Vinay
Amit
Mira
Arvind
Sagar

LinqExample02
Arjun
Krishna
Maya
Bhim
Nakul
Radha
Arvind
Sagar

No comments:

Post a Comment

Hot Topics