LINQ Best practices for C#

Improve C# programming with LINQ ( Part -1 ) 

The code written using LINQ is more understandable rather than the classic C# programming codes.
Below are 2 scenarios, where you can avoid some classic C# codes and use LINQ instead.



- If you need to fetch all objects from a list or array, with some conditions, then in classic C# you need a for or foreach loop and a if condition. Where as in LINQ a simple one line query will do that for you.
static void ForEachLoop()
        {
            List<Company> lstCompany = FetchCompanyDetails(); // Get the list of companies
            List<Company> lstCompanyInBhubaneswar = new List<Company>(); // List to hold the result company list
            foreach (var company in lstCompany)
            {
                if(company.City == "Bhubaneswar")
                {
                    lstCompanyInBhubaneswar.Add(company);
                }
            }
            // lstCompanyInBhubaneswar holds the company list that are presnt in bhubaneswar
        }

static void ForEachLoopUsingLinqSample()
        {
            List<Company> lstCompany = FetchCompanyDetails(); // Get the list of companies
            List<Company> lstCompanyInBhubaneswar = new List<Company>(); // List to hold the result company list
            lstCompanyInBhubaneswar = lstCompany.Where(company => company.City == "Bhubaneswar").ToList();
            // lstCompanyInBhubaneswar holds the company list that are presnt in bhubaneswar
        }
- If you need to fetch 2 recordings from a list, here is the sample code for C# and LINQ
/// <summary>
        /// Fetch 2 companies 
        /// </summary>
        static void SelectTopNRows()
        {
            List<Company> lstCompany = FetchCompanyDetails(); // Get the list of companies
            List<Company> lstCompanyInBhubaneswar = new List<Company>(); // List to hold the result company list
            foreach (Company company in lstCompany)
            {
                lstCompanyInBhubaneswar.Add(company);
                if (lstCompanyInBhubaneswar.Count() == 2)
                    break;
            }
        }
static void SelectTopNRowsUsingLINQSample()
        {
            List<Company> lstCompany = FetchCompanyDetails(); // Get the list of companies
            List<Company> lstCompanyInBhubaneswar = new List<Company>(); // List to hold the result company list
            lstCompanyInBhubaneswar = lstCompany.Take(2).ToList();

        }




Happy Coding...

No comments:

Post a Comment