linq to object in csharp

LINQ to Objects is a set of extension methods in the System.Linq namespace of C# that provides a powerful and easy way to query data collections. Here is an example of how to use LINQ to Objects to query a list of integers:

main.cs
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        // Query the list to get even numbers
        var evenNumbers = from n in numbers
                          where n % 2 == 0
                          select n;

        // Alternatively, you can compress the query syntax into method syntax
        // var evenNumbers = numbers.Where(n => n % 2 == 0);

        // Print the even numbers
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}
654 chars
26 lines

In this example, we create a list of integers and query it to get the even numbers using LINQ. The where clause filters out the odd numbers, and select projects the result to a sequence of even numbers. The result is an IEnumerable<int> that can be iterated over or converted to other data types. Note that you can also use method syntax to achieve the same result, as shown in the commented line.

gistlibby LogSnag