Tuesday, April 18, 2023

How do you use LINQ in .NET Core?

LINQ (Language Integrated Query) is a feature in .NET Core that allows you to write queries that can operate on collections of objects or data stored in a database. LINQ provides a consistent query syntax that can be used to query and manipulate data from different sources.

Here's an example of using LINQ to filter a list of objects based on a specific condition:

var persons = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "Mary", Age = 40 },
};

var result = persons.Where(p => p.Age > 30);


In this example, we have a list of Person objects and we want to filter them based on age. The LINQ query uses the Where method to filter the list, and the lambda expression (p => p.Age > 30) specifies the condition for filtering.

Here are some of the other common LINQ operators:

  • Select: projects each element of a sequence into a new form
  • OrderBy/OrderByDescending: sorts the elements of a sequence based on a specified key
  • GroupBy: groups the elements of a sequence based on a specified key
  • Join: performs an inner join on two sequences based on a specified key


In addition to querying in-memory collections, LINQ can also be used to query data stored in databases using LINQ to SQL or Entity Framework. Here's an example of using LINQ to SQL to query data from a database:

using (var context = new MyDbContext())
{
    var result = from p in context.Persons
                 where p.Age > 30
                 select p.Name;
}
 

In this example, we're querying a Persons table in a database using LINQ to SQL. The LINQ query uses the same syntax as querying an in-memory collection, but LINQ to SQL generates the appropriate SQL code to execute the query against the database.

 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.