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

LINQ with custom objects in C Sharp (C#)

Choose your learning style9 modes available
Introduction

LINQ helps you easily find, filter, or sort data inside lists of your own objects, like people or products.

You have a list of students and want to find those with grades above 90.
You want to sort a list of books by their publication year.
You need to filter employees who work in a specific department.
You want to select only the names from a list of customer objects.
Syntax
C Sharp (C#)
var result = from item in collection
             where condition
             select item;

collection is your list of custom objects.

condition is how you filter the objects.

Examples
Selects all people who are 18 or older.
C Sharp (C#)
var adults = from person in people
             where person.Age >= 18
             select person;
Selects only the names from the list of people.
C Sharp (C#)
var names = from person in people
            select person.Name;
Sorts books by their publication year.
C Sharp (C#)
var sortedBooks = from book in books
                  orderby book.Year
                  select book;
Sample Program

This program creates a list of people, then uses LINQ to find all who are 18 or older. It prints their names.

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

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 17 },
            new Person { Name = "Charlie", Age = 25 }
        };

        var adults = from person in people
                     where person.Age >= 18
                     select person.Name;

        foreach (var name in adults)
        {
            Console.WriteLine(name);
        }
    }
}
OutputSuccess
Important Notes

You can use LINQ with any list of your own objects.

LINQ queries are easy to read and write, like asking questions about your data.

Remember to include using System.Linq; to use LINQ features.

Summary

LINQ lets you filter, sort, and select data from lists of custom objects easily.

You write simple queries that look like questions about your data.

It works well with your own classes and properties.