Showing 30 question(s)

Answer:

LINQ (Language Integrated Query) is a feature in C# that allows developers to query collections, databases, XML, and other data sources using a consistent syntax.

Code Example:

var numbers = new List<int> { 1, 2, 3, 4, 5 };

var evenNumbers = numbers.Where(n => n % 2 == 0);

Tags:

Answer:

LINQ provides readable code, compile-time type checking, IntelliSense support, reduced boilerplate code, and a unified querying syntax for different data sources.

Code Example:

var products = productsList
    .Where(p => p.Price > 1000)
    .OrderBy(p => p.Name);

Tags:

Answer:

LINQ can query collections, arrays, lists, Entity Framework, SQL Server, XML documents, JSON data, and any data source implementing IEnumerable or IQueryable.

Code Example:

List<Employee>
Array
SQL Database
XML
Entity Framework

Tags:

Answer:

Query Syntax uses SQL-like keywords such as from, where, and select, while Method Syntax uses extension methods like Where(), Select(), and OrderBy().

Code Example:

// Query Syntax
var result =
    from e in employees
    where e.Salary > 50000
    select e;

// Method Syntax
var result = employees
    .Where(e => e.Salary > 50000);

Tags:

Answer:

IEnumerable<T> represents an in-memory collection that supports forward-only iteration. LINQ to Objects operates on IEnumerable.

Code Example:

IEnumerable<int> numbers =
    new List<int> { 1, 2, 3, 4 };

Tags:

Answer:

IQueryable<T> is used for querying remote data sources such as databases. The query is translated into SQL and executed by the database provider.

Code Example:

IQueryable<Employee> employees =
    context.Employees;

Tags:

Answer:

IEnumerable executes queries in memory after data is loaded, while IQueryable builds an expression tree that is translated into SQL and executed by the database.

Code Example:

IEnumerable -> In Memory

IQueryable -> Database

Tags:

Answer:

Where() filters a collection based on one or more conditions and returns only the matching elements.

Code Example:

var employees = employeesList
    .Where(e => e.Department == "IT");

Tags:

Answer:

Select() projects each element into a new form by selecting specific properties or transforming the data.

Code Example:

var names = employees
    .Select(e => e.Name);

Tags:

Answer:

SelectMany() flattens nested collections into a single sequence, making it useful for working with hierarchical data.

Code Example:

var courses = students
    .SelectMany(s => s.Courses);

Tags:

Answer:

OrderBy() sorts the elements of a collection in ascending order based on a specified key.

Code Example:

var employees = employeesList
    .OrderBy(e => e.Name);

Tags:

Answer:

OrderByDescending() sorts the elements of a collection in descending order based on a specified key.

Code Example:

var employees = employeesList
    .OrderByDescending(e => e.Salary);

Tags:

Answer:

ThenBy() performs secondary sorting after an OrderBy() operation using ascending order.

Code Example:

var employees = employeesList
    .OrderBy(e => e.Department)
    .ThenBy(e => e.Name);

Tags:

Answer:

ThenByDescending() performs secondary sorting in descending order after OrderBy() or OrderByDescending().

Code Example:

var employees = employeesList
    .OrderBy(e => e.Department)
    .ThenByDescending(e => e.Salary);

Tags:

Answer:

Count() returns the total number of elements in a collection or the number of elements that satisfy a condition.

Code Example:

int total = employees.Count();

int itEmployees = employees
    .Count(e => e.Department == "IT");

Tags:

Answer:

Sum() calculates the total of numeric values in a collection.

Code Example:

decimal totalSalary = employees
    .Sum(e => e.Salary);

Tags:

Answer:

Average() calculates the average value of a numeric property in a collection.

Code Example:

decimal averageSalary = employees
    .Average(e => e.Salary);

Tags:

Answer:

Min() returns the smallest value from a collection based on the specified selector.

Code Example:

decimal minimumSalary = employees
    .Min(e => e.Salary);

Tags:

Answer:

Max() returns the largest value from a collection based on the specified selector.

Code Example:

decimal maximumSalary = employees
    .Max(e => e.Salary);

Tags:

Answer:

GroupBy() groups elements that have the same key into collections. It is commonly used for reports and summaries.

Code Example:

var groups = employees
    .GroupBy(e => e.Department);

foreach (var group in groups)
{
    Console.WriteLine(group.Key);
}

Tags:

Answer:

Join() combines two collections based on matching keys, similar to an INNER JOIN in SQL.

Code Example:

var result = employees.Join(
    departments,
    e => e.DepartmentId,
    d => d.Id,
    (e, d) => new
    {
        e.Name,
        Department = d.Name
    });

Tags:

Answer:

GroupJoin() performs a grouped join where each element from the first collection is associated with a collection of matching elements from the second collection.

Code Example:

var result = departments.GroupJoin(
    employees,
    d => d.Id,
    e => e.DepartmentId,
    (d, emp) => new
    {
        Department = d.Name,
        Employees = emp
    });

Tags:

Answer:

First() returns the first element of a sequence. It throws an exception if the sequence is empty.

Code Example:

var employee = employees.First();

Tags:

Answer:

FirstOrDefault() returns the first matching element or the default value (null for reference types) if no matching element exists.

Code Example:

var employee = employees
    .FirstOrDefault(e => e.Id == 1);

Tags:

Answer:

Single() returns the only matching element. It throws an exception if there are no matches or more than one matching element.

Code Example:

var employee = employees
    .Single(e => e.Id == 1);

Tags:

Answer:

SingleOrDefault() returns the only matching element or the default value if none exists. It throws an exception if multiple matching elements are found.

Code Example:

var employee = employees
    .SingleOrDefault(e => e.Id == 1);

Tags:

Answer:

Skip() ignores a specified number of elements, while Take() returns a specified number of elements. They are commonly used for pagination.

Code Example:

var page = employees
    .Skip(20)
    .Take(10);

Tags:

Answer:

Deferred execution means a LINQ query is not executed until the results are actually enumerated, such as by using foreach(), ToList(), or ToArray().

Code Example:

var query = employees
    .Where(e => e.Salary > 50000);

// Executes here
var result = query.ToList();

Tags:

Answer:

Immediate execution occurs when methods such as ToList(), ToArray(), Count(), First(), or Single() execute the query immediately and return the results.

Code Example:

var employeesList = employees
    .Where(e => e.Department == "IT")
    .ToList();

Tags:

Answer:

Use meaningful query names, avoid multiple enumeration, prefer IQueryable for database queries, use Select() to fetch only required columns, use Any() instead of Count() for existence checks, and keep queries simple and readable.

Code Example:

// Good
bool exists = employees.Any(e => e.Id == 10);

// Avoid
bool exists = employees.Count(e => e.Id == 10) > 0;

Tags: