C# LINQ Basics

C# Code Snippets LINQ Basics
Share:

About

In this code snippet, we will learn how to do some basic queries using LINQ(Language Integrated Query) in C#.

LINQ is used to work with data within C# and can be used on enumerable types(IEnumerable<T> or IQueryable<T> interface) like listsarrays, … A query can be made by using an SQL query like syntax or by method chaining. The latter is often combined with the lambda operator to specify some kind of condition as the parameter to the function/method.

Note: To be able to use LINQ you will have to include the following namespace: using System.Linq;
Note: Use IntelliSense to see all the possible LINQ methods.

Let’s have a look at the code below to see how to use LINQ.

Query Code Snippets:

//LINQ query on array.
int[] numbers = { 1, 5, 8, 7, 5, 6, 2 };
var queryResult = from number in numbers
                  where number > 5
                  select number;


//The same LINQ query can be performed on an array or any type that implements the IEnumerable<T> or IQueryable<T> interface.
List<int> numbersList = new List<int>() { 1, 5, 8, 7, 5, 6, 2 };

var queryResult2 = from number in numbers
                  where number > 5
                  select number;


//The same type of query can also be done using the method/function syntax combined with the lambda operator for specifying the condition.
var queryResult3 = numbers.Where(x => x > 5);


//We can chain more functions to perform additional operations on the data.
var queryResult4 = numbers.Where(x => x > 2).OrderBy(x => x); //OrderByDescending also exists


//Here are a few more useful LINQ methods.
var queryResult5 = numbers.Where(x => x > 2).Distinct().Average(); //Distinct gets rid of any duplicates then we get the average of all the values.

var queryResult6 = numbers.First(); //Gets first element.

var queryResult7 = numbers.Last(); //Gets last element.

var queryResult8 = numbers.Max(); //Gets largest element.

var queryResult9 = numbers.Min(); //Gets smallest element.

var queryResult10 = numbers.Sum(); //Gets sum of all elements.

//You can even use object properties in the condition like so.
MyClass[] myClassList = new MyClass[] { new MyClass(5, 0), new MyClass(8, 4), new MyClass(9, 2) };

var queryResult11 = myClassList.Where(x => x.MyProperty > 1 && x.MyProperty2 > 1);

Full Code:

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

namespace LINQ
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("LINQ query on array: ");

            //LINQ query on array.
            int[] numbers = { 1, 5, 8, 7, 5, 6, 2 };

            var queryResult = from number in numbers
                              where number > 5
                              select number;

            foreach (var item in queryResult)
                Console.Write(item + " ");




            Console.WriteLine("");
            Console.Write("LINQ query on list: ");

            //The same LINQ query can be performed on an array or any type that implements the IEnumerable<T> or IQueryable<T> interface.
            List<int> numbersList = new List<int>() { 1, 5, 8, 7, 5, 6, 2 };

            var queryResult2 = from number in numbers
                              where number > 5
                              select number;

            foreach (var item in queryResult2)
                Console.Write(item + " ");




            Console.WriteLine("");
            Console.Write("LINQ query with function syntax: ");

            //The same type of query can also be done using the method/function syntax combined with the lambda operator for specifying the condition.
            var queryResult3 = numbers.Where(x => x > 5);

            foreach (var item in queryResult3)
                Console.Write(item + " ");




            Console.WriteLine("");
            Console.Write("LINQ query with method chaining: ");

            //We can chain more functions to perform additional operations on the data.
            var queryResult4 = numbers.Where(x => x > 2).OrderBy(x => x); //OrderByDescending also exists

            foreach (var item in queryResult4)
                Console.Write(item + " ");

            Console.WriteLine("");




            //Here are a few more useful LINQ methods.
            var queryResult5 = numbers.Where(x => x > 2).Distinct().Average(); //Distinct gets rid of any duplicates then we get the average of all the values.
            Console.WriteLine("Avereage function: " + queryResult5);

            var queryResult6 = numbers.First(); //Gets first element.
            Console.WriteLine("Get first element: " + queryResult6);

            var queryResult7 = numbers.Last(); //Gets last element.
            Console.WriteLine("Get last element:: " + queryResult7);

            var queryResult8 = numbers.Max(); //Gets largest element.
            Console.WriteLine("Largest element: " + queryResult8);

            var queryResult9 = numbers.Min(); //Gets smallest element.
            Console.WriteLine("Smallest element: " + queryResult9);

            var queryResult10 = numbers.Sum(); //Gets sum of all elements.
            Console.WriteLine("Sum of all elements: " + queryResult10);




            Console.Write("List of objects: ");

            //You can even use object properties in the condition like so.
            MyClass[] myClassList = new MyClass[] { new MyClass(5, 0), new MyClass(8, 4), new MyClass(9, 2) };

            var queryResult11 = myClassList.Where(x => x.MyProperty > 1 && x.MyProperty2 > 1);

            Console.WriteLine(queryResult11.First().MyProperty);




            Console.ReadLine();
        }

        class MyClass
        {
            public MyClass(int myProperty, int myProperty2)
            {
                MyProperty = myProperty;
                MyProperty2 = myProperty2;
            }

            public int MyProperty { get; set; }
            public int MyProperty2 { get; set; }
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger