0
0
C Sharp (C#)programming~5 mins

LINQ method syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

LINQ method syntax helps you easily work with collections like lists or arrays to find, filter, or change data.

You want to find all even numbers in a list.
You need to sort a list of names alphabetically.
You want to count how many items meet a condition.
You want to transform a list of numbers into their squares.
Syntax
C Sharp (C#)
collection.MethodName(arguments)
You chain methods like Where(), Select(), OrderBy() to work with data.
Each method returns a new collection or value based on the original.
Examples
Finds all even numbers from the 'numbers' list.
C Sharp (C#)
var evens = numbers.Where(n => n % 2 == 0);
Sorts the 'names' list alphabetically.
C Sharp (C#)
var namesSorted = names.OrderBy(name => name);
Creates a new list with squares of each number.
C Sharp (C#)
var squares = numbers.Select(n => n * n);
Sample Program

This program uses LINQ method syntax to find even numbers, get squares, and count even numbers in an array.

C Sharp (C#)
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6 };

        var evenNumbers = numbers.Where(n => n % 2 == 0);
        var squares = numbers.Select(n => n * n);
        var countEven = numbers.Count(n => n % 2 == 0);

        Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers));
        Console.WriteLine("Squares: " + string.Join(", ", squares));
        Console.WriteLine("Count of even numbers: " + countEven);
    }
}
OutputSuccess
Important Notes

LINQ methods do not change the original collection; they create new results.

Use lambda expressions (like n => n % 2 == 0) to specify conditions or transformations.

Summary

LINQ method syntax lets you work with collections easily using chainable methods.

Common methods include Where (filter), Select (transform), OrderBy (sort), and Count (count items).

It helps write clear and readable code for data operations.