Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Mastering LINQ by Samples - LINQ Basics

2.33/5 (3 votes)
23 Sep 2010CPOL 14.2K  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data;
namespace Linq_Basics
{
    class Program
    {
        static void Main(string[] args)
        {
            //Selecting all item from data source
            SelectAllfromDataSource();
            //Filtering items from data source
            FilteringData();
            //Filtering by type and ranges of elements
            FilteringTypeRanges();
            //Concatenate data sources
            ConcatenateDataSources();
            //Selecting with multiple members types
            Selecting_MultipleMembers();
            //Working with join and selecting from multiple data sources
            WorkingwithJoin();
            //Selecting with Grouping
            Grouping();
            //Selecting with Sorting
            Sorting();
            //Compare data sources
            Comparing();
            //Working with aggregation methods
            Aggregation();
            //Working with Let
            WorkingWithLet();
            //Converting from <IEnumerable>
            ConvertingFromIEnum();
            Console.Read();
        }
        static void ConvertingFromIEnum()
        {
            IEnumerable<PersonInfo> ds = InitializePersonInfo();

            //to array
            PersonInfo[] dsArray = ds.ToArray();
            //to list
            IList<PersonInfo> dsList = ds.ToList();
            //to dictionary
            Dictionary<string, PersonInfo> dsDict = ds.ToDictionary(k => k.Name);
            foreach (KeyValuePair<string, PersonInfo> item in dsDict)
            {
                Console.WriteLine(item.Key + "\t" + item.Value.Age);
            }
        }
        static void WorkingWithLet()
        {
            double[] marks = { 25, 44, 98, 70, 85, 35, 40, 66, 22, 75 };
            IEnumerable<double> validMarks = from mark in marks
                                             let avg = marks.Average()
                                             where mark >= avg
                                             select mark;
            Console.WriteLine("Average:{0} \nValid Marks:", marks.Average());
            foreach (double mark in validMarks)
            {
                Console.WriteLine(mark);
            }
        }
        
        static void Aggregation()
        {
            int[] ages = { 21, 25, 32, 23, 40, 36, 15, 18, 35 };

            //Standard
            Console.WriteLine(ages.Min());
            Console.WriteLine(ages.Max());
            Console.WriteLine(ages.Count());
            Console.WriteLine(ages.Sum());
            Console.WriteLine(ages.Average());
            Console.WriteLine("\n");

            //Custom Aggregation
            Console.WriteLine(ages.Aggregate((sum, item) => sum += item));
            
        }
        static void Comparing()
        {
            string[] col1 = { "Green", "Brown", "Blue" };
            string[] col2 = { "Green", "Brown", "Blue" };
            string[] col3 = { "Green", "Blue", "Brown" };

            Console.WriteLine(col1.SequenceEqual(col2));
            Console.WriteLine(col1.SequenceEqual(col3));

            //Working with Custom Comparator
            CustomCompartor cust = new CustomCompartor();
            Console.WriteLine(col1.SequenceEqual(col2, cust));
            Console.WriteLine(col1.SequenceEqual(col3, cust));
        }
        class CustomCompartor : IEqualityComparer<string>
        {
            public bool Equals(string x, string y)
            {
                return x[0]==y[0];
            }

            public int GetHashCode(string obj)
            {
                return obj[0].GetHashCode();
            }
        }
        static void Sorting()
        {
            IList<PersonInfo> personsList = InitializePersonInfo();

            //Sorting from lowest to biggest
            var ascSort = from p in personsList
                          orderby p.Age ascending
                          select new
                          {
                              p.Name,
                              p.Age
                          };
            foreach (var item in ascSort)
            {
                Console.WriteLine("Name:{0}\tAge:{1}", item.Name, item.Age);
            }
            Console.WriteLine("\n");
           
            //Sorting from biggest to lowest
            var descSort = from p in personsList
                           orderby p.Age descending
                           select new
                           {
                               p.Name,
                               p.Age
                           };
            foreach (var item in descSort)
            {
                Console.WriteLine("Name:{0}\tAge:{1}", item.Name, item.Age);
            }
        }


        static void Grouping()
        {
            IList<PersonInfo> perList = InitializePersonInfo();
            IEnumerable<IGrouping<bool, PersonInfo>> groupsIEnum = from p in perList
                                                                   group p by p.isMarr;
            //Method 1
            foreach (IGrouping<bool, PersonInfo> group in groupsIEnum)
            {
                Console.WriteLine("IsMarr:{0}", group.Key);
                foreach (PersonInfo item in group)
                {
                    Console.WriteLine(item.Name);
                }
                Console.WriteLine("\n");
            }
            Console.WriteLine("\n");

                         
        }

        static void WorkingwithJoin()
        {
            IList<PersonInfo> PerInfoList = InitializePersonInfo();
            IList<EmployeeInfo> EmpInfoList = InitializeEmployeeInfo();
            var joinVar = from p in PerInfoList
                          join e in EmpInfoList on p.Name equals e.Name
                          select new
                          {
                              p.Name,
                              p.isMarr,
                              p.Age,
                              e.JobTitle
                          };
            foreach (var item in joinVar)
            {
                Console.WriteLine("{0}\t{1}\t{2}\t{3}", item.Name, item.isMarr, item.Age, item.JobTitle);
            }
        }
        static IList<EmployeeInfo> InitializeEmployeeInfo()
        {
            return new List<EmployeeInfo>()
            {
                new EmployeeInfo{Name="Steve",JobTitle="Software Developer"},
                new EmployeeInfo{Name="Tim",JobTitle="Web Developer"}
            };
        }

        class EmployeeInfo
        {
            public string JobTitle;
            public string Name;
        }

        static void Selecting_MultipleMembers()
        {
            IList<PersonInfo> personList = InitializePersonInfo();
            var varPL = from it in personList
                        select new
                        {
                            it.Name,
                            it.Age,
                            it.isMarr
                        };
            foreach (var item in varPL)
            {
                Console.WriteLine("Name:{0}\tAge:{1}\tIsMarr:{2}", item.Name, item.Age, item.isMarr);
            }
        }
        static IList<PersonInfo> InitializePersonInfo()
        {
            return new List<PersonInfo>()
            {
                new PersonInfo{Name="Joseph",Age=27,isMarr=true},
                new PersonInfo{Name="John",Age=25,isMarr=false},
                new PersonInfo{Name="Steve",Age=30,isMarr=true}
            };
        }
        class PersonInfo
        {
            public string Name;
            public int Age;
            public bool isMarr;
        }

        static void ConcatenateDataSources()
        {
            string[] colA = { "Red", "Orange", "Green" };
            string[] colB = { "Blue", "Brown", "Pink" };
            string[] colC = { "Black", "White", "Yellow" };

            IEnumerable<string> con1IEnum = colA.Concat<string>(colB);
            foreach (string item in con1IEnum)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            IEnumerable<string> con2IEnum = colA.Concat<string>(colB).Concat<string>(colC);
            foreach (string item in con2IEnum)
            {
                Console.WriteLine(item);
            }
        }     


        static void FilteringTypeRanges()
        {
            //Getting items by type
            IList<object> mixList = InitializeMix();
            IEnumerable<string> getstringIEnum = mixList.OfType<string>();
            foreach (string item in getstringIEnum)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            int[] intArr = { 1, 2, 3, 4, 5, 6 };
            IEnumerable<int> skipIEnum = intArr.Skip(3);
            foreach(int item in skipIEnum)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            IEnumerable<int> takeIEnum = intArr.Take(3);
            foreach (int item in takeIEnum)
            {
                Console.WriteLine(item);
            }
            
        }
        static IList<object> InitializeMix()
        {
            return new List<object>()
            {
                125,
                false,
                "WPF",
                50.5,
                "WCF",
                120,
                true
            };
        
        }

        static void FilteringData()
        {
            string[] carTypes ={"Honda","Lexus","Mazda","Toyota","Nissan",
                                  "Audi","BMW","Mercedes-Benz","Ford","Maybach",
                                  "Hummer","Mini","Mercury"};
           
            //Filtering by first char
            IEnumerable<string> filterM = from it in carTypes
                                          where it[0] == 'M'
                                          select it;
            foreach (string item in filterM)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            //Filtering by last char
            IEnumerable<string> filterA = from it in carTypes
                                          where it[it.Length - 1] == 'a'
                                          select it;
            foreach (string item in filterA)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            //Combining filters            
            IEnumerable<string> filterMA = from it in carTypes
                                           where it[0] == 'M' && it[it.Length - 1] == 'a'
                                           select it;
            foreach (string item in filterMA)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");
            
        IEnumerable<string> multiFilter=from it in carTypes
                                        where it[0]=='H' where it.Length<6
                                        select it;

        foreach (string item in multiFilter)
        {
            Console.WriteLine(item);
        }
        }

        static void SelectAllfromDataSource()
        {
            string[] plsArray = InitializeStrArray();
            IEnumerable<string> plsIEnum = from it in plsArray select it;
            foreach (string item in plsIEnum)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            IList<string> winList = InitializeList();
            IEnumerable<string> winIEnum = from it in winList select it;
            foreach (string item in winIEnum)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            DataTable namesTable = InitializeTable();
            IEnumerable<DataRow> namesIEnum = from it in namesTable.AsEnumerable() select it;
            foreach (DataRow item in namesIEnum)
            {
                Console.WriteLine(item["Name"]);
            }
            Console.WriteLine("\n");

            XElement dataXElement = InitializeXElement();
            IEnumerable<XElement> dataIEnum = from it in dataXElement.Elements() select it;
            foreach (string item in dataIEnum)
            {
                Console.WriteLine(item);
            }
        }
        static string[] InitializeStrArray()
        {
            return new string[]
            {
                "C Sharp",
                "Visual Basic",
                "C Plus Plus",
                "F Sharp"
            };
        }
        static IList<string> InitializeList()
        {
            return new List<string>()
            {
                "WPF",
                "WCF",
                "WF"
            };
        }
        static DataTable InitializeTable()
        {
            DataTable ret = new DataTable();
            ret.Columns.Add(new DataColumn("Name",typeof(string)));
            DataRow newRow=ret.NewRow();
            newRow["Name"]="Joseph";
            ret.Rows.Add(newRow);
            newRow=ret.NewRow();
            newRow["Name"]="Steve";
            ret.Rows.Add(newRow);
            return ret;
        }
        static XElement InitializeXElement()
        {
            return new XElement("Data", new XElement("Name", "ADO.NET"), new XElement("Name", "LINQ"), new XElement("Name", "Entity Framework"));
        }   
        
        
    }

  
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)