Skip to main content

LINQ queries



string[] arr= new string[]{"Anish","Jeeba","Jiya"};



  • IEnumerable<string> obj= (from item in arr select $"{item} is my name").ToList();
using let 

var result=from a in arr
let name= a.StartsWith('a')
where name
select a;

let acts as a temporary storage.

List<List<SampleList>> sam=new List<List<SampleList>>{
new List<SampleList>
{
new List<SampleList> { new SampleList{Name="Anish", number=31, Gender="M"}, new SampleList{Name="Anish", number=61, Gender="M"} }, new List<SampleList> { new SampleList{Name="Jeeba", number=12, Gender="F"}, new SampleList{Name="Jiya", number=44, Gender="F"} }, new List<SampleList> { new SampleList{Name="libu", number=12, Gender="M"}, new SampleList{Name="Vipin", number=55, Gender="F"} }
};

var x= (from s in sam
let val=s
from v in val
where v.number > 32
select new SampleList{
Name= v.Name,
number= v.number,
}).ToList();

Usage of let: for example to store the temporary result. In the below example we store the square value and avoid repetition.

List<List<int>> li=new List<List<int>>{
new List<int>{1,2,3},
new List<int>{6,7,8},
};

var res= from l in li
from z in l
let square=z*z
where square > 50
select z;

Group By

var res = from s in sam
                      from x in s
                     // where x.number > 18  Conditions can also be added
                      group x by x.Gender;

 foreach (var item in res)
            {
                Console.WriteLine($"{item.Key}");
                foreach (var i in item)
                    Console.WriteLine($"  {i.Name} : {i.number}");
            }

OR

var output = res.Select(i => new
            {
                key = i.Key,
                data = i.Select(z => new SampleList { Gender = z.Gender, Name = z.Name, number = z.number }).ToList()
            });

foreach (var item in output)
            {
                Console.WriteLine($"Lambda: {item.key}");
                foreach (var i in item.data)
                    Console.WriteLine($"   {i.Name} : {i.number}");
            }



Since we have grouped the data based on gender. So gender becomes the Key and the data is present in the inner loop.

First Letter of the Name Group

var alphabetGroup = from s in sam
                                from x in s
                                group x by x.Name[0];


By Multiple Keys

We group the data based on gender and number

var multipleKeys = from s in sam
                               from x in s
                               group x by new { x.Gender, x.number };



If we need to further order our data, we will need to create another query (as the query needs to end in a group by or select statement) and order the data accordingly. But we can use the into keyword to perform this operation in the same query.

INTO 

var multInto = from s in sam
                           from x in s
                           group x by new { x.number, x.Gender } into newGroup
                           orderby newGroup.Key.number

                           select $"{newGroup.Key.Gender}: {newGroup.Count()} ";


Group based on a key that does not exist (Usage of let)

Group based on age in the list given below. Such that numbers less than 18 fall under category "kid", >  18 "Boy" and > 50 "Old". We cannot use if else , but we can use the ternary operations.

 List<int> ageList = new List<int> { 1, 2, 3, 44, 55, 66, 77, 88 };

            var res = from age in ageList
                     let x = age > 18 ?
                                (age > 50) ? "Old" : "Boy"
                            : "kid"
                      group age by x into sample
                      select new {
                          key=sample.Key,
                          count=sample.Count(),
                          data=sample
                      };

            foreach (var item in res)
            {
                Console.WriteLine($"{item.key}: {item.count}");
                foreach (var i in item.data)
                {
                    Console.WriteLine($"  {i}");
                }


            }





 List<List<SampleList>> sam = new List<List<SampleList>>{
            new List<SampleList>
            {
               new SampleList{Name="Anish", number=31, Gender="M"},
               new SampleList{Name="Anish", number=61, Gender="M"}
            },
            new List<SampleList>
            {
                new SampleList{Name="Jeeba", number=12, Gender="F"},
                new SampleList{Name="Jiya", number=44, Gender="F"}
            },
            new List<SampleList>
            {
                new SampleList{Name="libu", number=31, Gender="M"},
                new SampleList{Name="Vipin", number=55, Gender="F"}
            },
            };

            List<List<SampleList2>> sam1 = new List<List<SampleList2>>{
            new List<SampleList2>
            {
               new SampleList2{Name1="abc", number1=31, Gender1="M"},
               new SampleList2{Name1="xyz", number1=62, Gender1="M"}
            },
            new List<SampleList2>
            {
                new SampleList2{Name1="fff", number1=12, Gender1="F"},
                new SampleList2{Name1="Jiya", number1=45, Gender1="F"}
            },
            new List<SampleList2>
            {
                new SampleList2{Name1="eee", number1=24, Gender1="M"},
                new SampleList2{Name1="vvv", number1=55, Gender1="F"}
            },
            };

Getting Inner data using SelectMany

 var s2 = sam.SelectMany(i => i.Select(z => new SampleList
            { number = z.number, Gender = z.Gender, Name = z.Name })).ToList();


Left Join

For every item in s2 , check if we have an entry. group matching records in s1 and if no records exist then display "no name available"

var res1 = (from sIn in s1
                      join sin2 in s2 on sIn.number1 equals sin2.number into g
                      select new
                      {
                          sss = g.DefaultIfEmpty(new SampleList() {
                              Name="No Name",
                              Gender="NA",
                              number=0
                          }).ToList(),
                          NameS=sIn.Name1,
                          NumS=sIn.number1
                      }).ToList();


Comments