أسئلة القسم

تدرب على أسئلة المقابلات في هذا القسم. اكتب إجابتك، قم بتقييمها، أو اضغط على "عرض الإجابة" بعد التفكير.

What is LINQ in .NET, and how does Fluent API relate? سهل

LINQ (Language Integrated Query) → A set of features that brings query capabilities into C#.

Fluent API → A style of writing LINQ queries using method chaining (.Where().Select()) instead of SQL-like syntax.

Both achieve the same goal; Fluent API is essentially method syntax.

What are the advantages of using LINQ over traditional SQL queries or loops? سهل
  • Strongly typed, compile-time checking.
  • IntelliSense support in Visual Studio.
  • Readable and maintainable code.
  • Consistent querying across objects, XML, SQL, EF, etc.
What are Anonymous Types in LINQ, and when would you use them? سهل

Allow you to project results into objects without defining a class.

var result = from e in employees
             select new { e.Name, e.Salary };

Useful for temporary data shapes in queries.

What is the difference between Method Syntax and Query Syntax in LINQ? Which one is better? سهل

Query syntax → SQL-like (from e in employees where e.Age > 30 select e;).

Method syntax → Fluent chaining (employees.Where(e => e.Age > 30)).

Both compile to the same IL. Method syntax is more powerful (supports Join, GroupBy, etc.).

Explain LINQ, including deferred execution, streaming, the IEnumerable/IEnumerator interfaces. متوسط

LINQ queries are not executed immediately → they run only when iterated (foreach, ToList()).

IEnumerable → Exposes an enumerator to iterate collections.

Deferred execution enables query reusability but can cause unexpected repeated DB calls.

What is the difference between LINQ to Objects, LINQ to SQL, and LINQ to Entities? متوسط

LINQ to Objects → Works on in-memory collections (List).

LINQ to SQL → Queries SQL Server directly, maps results to objects.

LINQ to Entities (EF) → Queries database via Entity Framework, supports multiple providers.

What is the difference between Select and SelectMany in LINQ? متوسط

Select → Projects each element into a new form.

SelectMany → Flattens collections of collections.

// Select returns list of lists
students.Select(s => s.Subjects);
// SelectMany flattens into single list
students.SelectMany(s => s.Subjects);
What is the difference between First(), FirstOrDefault(), Single(), and SingleOrDefault() in LINQ? متوسط

First() → Returns first element, throws if none.

FirstOrDefault() → Returns first or null/default.

Single() → Expects exactly one element, throws if none/multiple.

SingleOrDefault() → Same as Single but returns default if none.

What is the difference between Take, Skip, and TakeWhile in LINQ? متوسط

Take(n) → First n items.

Skip(n) → Skips first n items.

TakeWhile(cond) → Takes items until condition fails.

What is the difference between Any(), All(), and Contains() in LINQ? متوسط

Any() → Returns true if at least one element matches.

All() → Returns true if all elements match.

Contains() → Checks if collection contains an element.

Write LINQ query to get 2nd Highest Salary. متوسط

2nd Highest Salary:

var second = employees.OrderByDescending(e => e.Salary)
                      .Skip(1)
                      .FirstOrDefault();
What is GroupBy in LINQ? Can you give an example? متوسط

GroupBy is used to group elements of a sequence based on a key selector.

It returns a sequence of groups, where each group is an IGrouping<TKey, TElement>

var students = new[]
{
    new { Name = "Ali", Department = "CS" },
    new { Name = "Sara", Department = "CS" },
    new { Name = "John", Department = "IT" }
};

var grouped = students.GroupBy(s => s.Department);

foreach (var group in grouped)
{
    Console.WriteLine($"Department: {group.Key}");
    foreach (var student in group)
        Console.WriteLine($"  {student.Name}");
}
What is Join in LINQ? Explain inner join vs left join with example. متوسط

Join combines sequences based on matching keys.

Inner Join: Only includes matching elements from both sequences.

Left Join: Includes all elements from the left sequence and matches from the right (null if no match).

Example (Inner Join):

var students = new[] { new { Id = 1, Name = "Ali" }, new { Id = 2, Name = "Sara" } };
var departments = new[] { new { Id = 1, Dept = "CS" } };

var innerJoin = students.Join(
    departments,
    s => s.Id,
    d => d.Id,
    (s, d) => new { s.Name, d.Dept });

/* Output: Ali - CS */

Example (Left Join using GroupJoin + DefaultIfEmpty):

var leftJoin = students.GroupJoin(
    departments,
    s => s.Id,
    d => d.Id,
    (s, d) => new { s.Name, Dept = d.FirstOrDefault()?.Dept ?? "No Dept" });

/* Output: Ali - CS Sara - No Dept */

What is the difference between IEnumerable and IQueryable in the context of Entity Framework? متوسط
Feature IEnumerable IQueryable
Namespace System.Collections System.Linq
Execution In-memory (client-side) Remote (server-side, DB query)
Deferred Exec Yes Yes
Suitable for Small in-memory collections Large data, DB queries
Explain the concept of Expression Trees in LINQ. صعب

An expression tree represents code as a data structure (an object graph).

LINQ providers like EF Core use them to translate C# expressions into SQL.

They live in System.Linq.Expressions.

What happens when you write LINQ queries on in-memory collections vs databases? صعب

In-memory (LINQ to Objects):

Operates directly on IEnumerable.

Uses C# delegates and executes in the CLR.

Example: List.Where(...) runs fully in memory.

Database (LINQ to Entities/SQL):

Operates on IQueryable.

Translates the expression tree into SQL.

Query executed on DB server, results materialized into objects

Example:

// In-memory
var local = list.Where(x => x > 10);  // runs in CLR

// EF Core -> SQL
var dbQuery = db.Users.Where(x => x.Age > 18); // translated to SELECT ... WHERE Age > 18

Key difference: Execution location (memory vs DB).