DEV Community

Cover image for C# LINQ and LINQ Methods
Njeri Muriithi
Njeri Muriithi

Posted on

C# LINQ and LINQ Methods

Language-Integrated Query (LINQ)
is the name for a set of technologies based on the integration of query capabilities directly into the C# language.

The LINQ provides a clear and consistent way to query objects , relational databases and XML.

Contents

  1. LINQ Methods

There are two ways of expressing LINQ:

  1. Query Syntax: is similar to structured query language(SQL) for databases.

It begins with From keyword and ends with Select or Group By clause.

2.Method /fluent syntax: Comprises of extension methods and lamba expressions . The extension Methods are included in the Enumerable and Queryable classes.

Method syntax Example showing the extension method and the labda expression

The query syntax is converted to method syntax at compile time.

Note :

LINQ does not directly modify data it provides a way to query and transform data such as filtering, sorting, and ordering.

This article will focus on using method syntax.

LINQ Methods

There are several LINQ Methods:

1.Any()

This type determines whether the defined collection contains any of the elements defined and returns a boolean. True if any of the elements pass the test otherwise false.

Example 1:list of Names.

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

public class LinQ
{
    public static void Main()
    {
        IList<string> Names = new List<string> { "John", "James", "Kevin", "Joan" };

        var isNameContainsJohn = Names.Any(name => name == "John");
        var isNames  = Names.Any();
        Console.WriteLine($" Name contains John -> {isNameContainsJohn}");
        Console.WriteLine($"Does Names Contain any Elements -> {isNames}");
    }
}
Enter fullscreen mode Exit fullscreen mode
Output: 
 > Name contains John -> True
 > Does Names Contain any Elements -> True
Enter fullscreen mode Exit fullscreen mode

Example 2: List of Numbers

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

public class LinQ
{
    public static void Main()
    {


        IList<int> Numbers = new List<int>{1,2,4,5,6,7};
        var isAnyNumberGreaterThan10 = Numbers.Any(Num => Num>10);
        Console.WriteLine($"Is Any NumberGreaterThan10 -> {isAnyNumberGreaterThan10}");



    }
}
Enter fullscreen mode Exit fullscreen mode
OutPut:
>Is Any NumberGreaterThan10 -> False
Enter fullscreen mode Exit fullscreen mode

Your feedback on how I can make this article even better/more helpful is most appreciated!

Thank you for reading❤️️

Top comments (0)