Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

Popular tracks

LINQ LINQ Tutorial · LINQ

Concat(seq2);

var result = string.Join(", ", concatenated);

Console.WriteLine(result); // Output: Alice, Bob, Charlie, David

Permalink

LINQ LINQ Tutorial · LINQ

Filters employees whose department is "IT".

Permalink

LINQ LINQ Tutorial · LINQ

Projects only the Name property of each employee.

Permalink

LINQ LINQ Tutorial · LINQ

Orders the list from highest salary to lowest.

Permalink

LINQ LINQ Tutorial · LINQ

Combines filtering + projection using anonymous types.

Permalink

LINQ LINQ Tutorial · LINQ

Counts only employees matching the condition.

Permalink

LINQ LINQ Tutorial · LINQ

What is the average salary in IT?

double avgSalary = employees

.Where(e => e.Department == "IT")

.Average(e => e.Salary);

Permalink

LINQ LINQ Tutorial · LINQ

Find the highest salary in the company

double max = employees.Max(e => e.Salary);

Permalink

LINQ LINQ Tutorial · LINQ

Each group is an IGrouping<string, Employee>

Permalink

LINQ LINQ Tutorial · LINQ

For each department, show average salary

var avgByDept = employees

.GroupBy(e => e.Department)

.Select(g => new

Department = g.Key,

AverageSalary = g.Average(e => e.Salary)

});

Permalink

LINQ LINQ Tutorial · LINQ

join matches based on keys.

Permalink

LINQ LINQ Tutorial · LINQ

Uses DefaultIfEmpty() to simulate outer join.

Permalink

LINQ LINQ Tutorial · LINQ

Get first employee with salary > 80000

var highPaid = employees.FirstOrDefault(e => e.Salary > 80000);

Permalink

LINQ LINQ Tutorial · LINQ

Use Single vs First — what's the difference?

var onlyHR = employees.SingleOrDefault(e => e.Id == 1); // throws if

var firstHR = employees.FirstOrDefault(e => e.Id == 1); // safe

✅ Tip: Use Single when you're sure there will be exactly one result.

Permalink

LINQ LINQ Tutorial · LINQ

Find employees in both List A and List B

var listA = employees.Take(3);

var listB = employees.Skip(2);

var common = listA.Select(e => e.Id)

.Intersect(listB.Select(e => e.Id));

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Get employees in List A but not in List B

var onlyInA = listA.Select(e => e.Id)

.Except(listB.Select(e => e.Id));

Permalink

LINQ LINQ Tutorial · LINQ

Skip top 2 highest salaries and take next 2

var result = employees

.OrderByDescending(e => e.Salary)

.Skip(2)

.Take(2);

Permalink

LINQ LINQ Tutorial · LINQ

Are all employees earning more than 50k?

bool allHigh = employees.All(e => e.Salary > 50000);

Permalink

LINQ LINQ Tutorial · LINQ

Are there any employees in “Legal” department?

bool anyLegal = employees.Any(e => e.Department == "Legal");

Permalink

LINQ LINQ Tutorial · LINQ

This forces query execution (immediate execution).

Permalink

LINQ LINQ Tutorial · LINQ

let stores computed value for reuse.

Permalink

LINQ LINQ Tutorial · LINQ

Why is LINQ deferred?

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

employees.Add(new Employee { Id = 6, Name = "Frank", Department =

"IT", Salary = 90000 });

foreach (var emp in query)

Console.WriteLine(emp.Name);

✅ Output includes “Frank” — because query is executed at enumeration time.

Permalink

LINQ LINQ Tutorial · LINQ

Get top 3 highest-paid employees

var top3 = employees

.OrderByDescending(e => e.Salary)

.Take(3);

Permalink

LINQ LINQ Tutorial · LINQ

Get bottom 2 lowest-paid employees

var bottom2 = employees

.OrderBy(e => e.Salary)

.Take(2);

Permalink

LINQ LINQ Tutorial · LINQ

Get names of employees whose names start with 'A'

var namesStartingA = employees

.Where(e => e.Name.StartsWith("A"))

.Select(e => e.Name);

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Get total salary by department

var totalByDept = employees

.GroupBy(e => e.Department)

.Select(g => new {

Department = g.Key,

Total = g.Sum(e => e.Salary)

});

Permalink

LINQ LINQ Tutorial · LINQ

Flatten list of lists using SelectMany

List<List<int>> numbers = new() {

new() { 1, 2 },

new() { 3, 4 },

new() { 5 }

var flat = numbers.SelectMany(n => n);

Permalink

LINQ LINQ Tutorial · LINQ

Use Distinct() on names

var distinctNames = employees

.Select(e => e.Name)

.Distinct();

Permalink

LINQ LINQ Tutorial · LINQ

Convert list of salaries to array

double[] salaryArray = employees

.Select(e => e.Salary)

.ToArray();

Permalink

LINQ LINQ Tutorial · LINQ

Find duplicate departments

var duplicateDepts = employees

Follow :

.GroupBy(e => e.Department)

.Where(g => g.Count() > 1)

.Select(g => g.Key);

Permalink

LINQ LINQ Tutorial · LINQ

Compare LINQ to SQL vs LINQ to Objects?

Answer:

  • LINQ to Objects runs in memory on collections (List<T>, arrays).
  • LINQ to SQL/EF builds expression trees and translates to SQL queries.
Permalink

LINQ LINQ Tutorial · LINQ

Show all departments even if no employees (outer join)

var allDepts = from d in departments

join e in employees on d.Name equals e.Department

into empGroup

from eg in empGroup.DefaultIfEmpty()

select new {

Dept = d.Name,

EmpName = eg?.Name ?? "No Employee"

Permalink

LINQ LINQ Tutorial · LINQ

Use Zip() to combine two lists

var names = new[] { "A", "B", "C" };

var scores = new[] { 10, 20, 30 };

var zipped = names.Zip(scores, (n, s) => $"{n} scored {s}");

Permalink

LINQ LINQ Tutorial · LINQ

Filter only numeric strings using OfType<T>()

object[] mixed = { "One", 2, "Three", 4 };

var numbers = mixed.OfType<int>();

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Group by multiple fields (composite key)

var grouped = employees

.GroupBy(e => new { e.Department, e.Salary });

Permalink

LINQ LINQ Tutorial · LINQ

Paginate: Get page 2, size 3

int pageSize = 3;

int pageIndex = 2;

var page = employees

.Skip((pageIndex - 1) * pageSize)

.Take(pageSize);

Permalink

LINQ LINQ Tutorial · LINQ

Why use AsEnumerable()?

var query = dbContext.Employees

.AsEnumerable() // switch to in-memory

.Where(e => CustomFunction(e.Name));

✅ Use when your logic can't be translated to SQL.

Permalink

LINQ LINQ Tutorial · LINQ

Detect and avoid N+1 query in EF?

Use Include() to load related entities:

var orders = dbContext.Orders

.Include(o => o.Customer)

.ToList();

Permalink

LINQ LINQ Tutorial · LINQ

How to force immediate execution?

  • Use .ToList(), .ToArray(), .Count(), .First() etc.

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Can we use LINQ on JSON?

✅ Yes — using System.Text.Json or Newtonsoft.Json, then LINQ on parsed objects.

Permalink

LINQ LINQ Tutorial · LINQ

How to create a dummy sequence of numbers from 1 to 10?

var numbers = Enumerable.Range(1, 10);

Permalink

LINQ LINQ Tutorial · LINQ

Repeat a value 5 times?

var fives = Enumerable.Repeat("Hi", 5);

Permalink

LINQ LINQ Tutorial · LINQ

What does DefaultIfEmpty() do?

Returns a default value if the sequence is empty (e.g. in left join).

Permalink

LINQ LINQ Tutorial · LINQ

How to write a subquery?

var topEarners = employees

.Where(e => e.Salary > employees.Average(x => x.Salary));

Permalink

LINQ LINQ Tutorial · LINQ

Check if a department has more than 2 employees?

bool deptCheck = employees

.Count(e => e.Department == "IT") > 2;

Permalink

LINQ LINQ Tutorial · LINQ

Create dictionary from list

var empDict = employees.ToDictionary(e => e.Id);

Permalink

LINQ LINQ Tutorial · LINQ

Sum salary by department, only if salary > 70k

Follow :

var sum = employees

.Where(e => e.Salary > 70000)

.GroupBy(e => e.Department)

.Select(g => new { g.Key, Sum = g.Sum(e => e.Salary) });

Permalink

LINQ LINQ Tutorial · LINQ

Find duplicate names

var dupNames = employees

.GroupBy(e => e.Name)

.Where(g => g.Count() > 1)

.Select(g => g.Key);

Permalink

LINQ LINQ Tutorial · LINQ

Merge two employee lists

var merged = list1.Union(list2);

Permalink

LINQ LINQ Tutorial · LINQ

Select only employees with even ID

var evens = employees.Where(e => e.Id % 2 == 0);

Permalink

LINQ LINQ Tutorial · LINQ

Reverse the order

var reversed = employees.Reverse();

Permalink

LINQ LINQ Tutorial · LINQ

Print all names in single comma-separated string

string result = string.Join(", ", employees.Select(e => e.Name));

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Safely get the first employee or null

var first = employees.FirstOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

How to handle exceptions in LINQ?

Use try-catch around enumeration, not the query:

try {

var result = employees.First(e => e.Salary > 999999);

} catch (Exception ex) {

Console.WriteLine("No match found.");

Permalink

LINQ LINQ Tutorial · LINQ

What's the difference between Select() and SelectMany()?

  • Select() returns collection of collections.
  • SelectMany() flattens them.
Permalink

LINQ LINQ Tutorial · LINQ

Chaining multiple Where() calls

var result = employees

.Where(e => e.Salary > 70000)

.Where(e => e.Department == "IT");

Permalink

LINQ LINQ Tutorial · LINQ

Nested grouping: Department → Salary Brackets

var nested = employees

.GroupBy(e => e.Department)

.Select(g => new {

Dept = g.Key,

SalaryGroups = g.GroupBy(e => e.Salary >= 80000 ? "High" :

"Low")

});

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Find longest employee name

var longest = employees

.OrderByDescending(e => e.Name.Length)

.FirstOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

Case-insensitive filtering

var hr = employees

.Where(e => e.Department.Equals("hr",

StringComparison.OrdinalIgnoreCase));

Permalink

LINQ LINQ Tutorial · LINQ

Select employee with second-highest salary

var secondHighest = employees

.OrderByDescending(e => e.Salary)

.Skip(1)

.FirstOrDefault();

✅ Skips the top salary and selects the next one.

Permalink

LINQ LINQ Tutorial · LINQ

Find employee with longest name

var longestName = employees

.OrderByDescending(e => e.Name.Length)

.FirstOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

Group employees by salary range (Low/High)

var salaryGroups = employees

.GroupBy(e => e.Salary > 75000 ? "High" : "Low")

.Select(g => new { Range = g.Key, Count = g.Count() });

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Get last employee alphabetically by name

var lastName = employees

.OrderBy(e => e.Name)

.LastOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

Get average salary of all employees

var avg = employees.Average(e => e.Salary);

Permalink

LINQ LINQ Tutorial · LINQ

Count distinct departments

var deptCount = employees

.Select(e => e.Department)

.Distinct()

.Count();

Permalink

LINQ LINQ Tutorial · LINQ

Find employee with lowest salary

var lowest = employees

.OrderBy(e => e.Salary)

.FirstOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

Remove duplicates from a list of strings

var items = new List<string> { "apple", "Apple", "banana", "apple"

var distinct = items

.Distinct(StringComparer.OrdinalIgnoreCase);

Permalink

LINQ LINQ Tutorial · LINQ

Group employees by first letter of name

var groupedByFirstLetter = employees

.GroupBy(e => e.Name[0])

.Select(g => new { Letter = g.Key, Employees = g.ToList() });

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Generate comma-separated string of all names

var result = string.Join(", ", employees.Select(e => e.Name));

Permalink

LINQ LINQ Tutorial · LINQ

Filter employees whose name contains 'a' (case-insensitive)

var filtered = employees

.Where(e => e.Name.IndexOf('a',

StringComparison.OrdinalIgnoreCase) >= 0);

Permalink

LINQ LINQ Tutorial · LINQ

Join two lists with different types

var result = from e in employees

join d in departments on e.Department equals d.Name

select new { e.Name, DeptLocation = d.Location };

Permalink

LINQ LINQ Tutorial · LINQ

Find the department with the most employees

var mostPopulated = employees

.GroupBy(e => e.Department)

.OrderByDescending(g => g.Count())

.FirstOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

Find names of employees with even-length names

var evenNames = employees

.Where(e => e.Name.Length % 2 == 0)

.Select(e => e.Name);

Permalink

LINQ LINQ Tutorial · LINQ

Custom sort by name length, then alphabetically

var customSort = employees

.OrderBy(e => e.Name.Length)

.ThenBy(e => e.Name);

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Find if all employees earn above 50k

bool allAbove50k = employees.All(e => e.Salary > 50000);

Permalink

LINQ LINQ Tutorial · LINQ

Find if any employee earns exactly 75000

bool exact = employees.Any(e => e.Salary == 75000);

Permalink

LINQ LINQ Tutorial · LINQ

Create lookup (multi-dictionary) of employees by department

var lookup = employees.ToLookup(e => e.Department);

Permalink

LINQ LINQ Tutorial · LINQ

Select department names that start with ‘F’

var deptNames = departments

.Where(d => d.Name.StartsWith("F"))

.Select(d => d.Name);

Permalink

LINQ LINQ Tutorial · LINQ

Combine employee names with their department (string format)

var combined = employees.Select(e => $"{e.Name} - {e.Department}");

Permalink

LINQ LINQ Tutorial · LINQ

Find employees in 'IT' with salary > 80k

var itHighEarners = employees

.Where(e => e.Department == "IT" && e.Salary > 80000);

Permalink

LINQ LINQ Tutorial · LINQ

Skip first and last employee

var middle = employees

.Skip(1)

.Take(employees.Count - 2);

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Find median salary (approx)

var salaries = employees.Select(e => e.Salary).OrderBy(s =>

s).ToList();

double median = salaries.Count % 2 == 0

? (salaries[salaries.Count / 2 - 1] + salaries[salaries.Count /

2]) / 2

: salaries[salaries.Count / 2];

Permalink

LINQ LINQ Tutorial · LINQ

Use SelectMany to flatten nested collections

var nested = new List<List<string>> {

new() { "A", "B" },

new() { "C", "D" }

var flat = nested.SelectMany(x => x);

Permalink

LINQ LINQ Tutorial · LINQ

Match employees with same salary

var duplicates = employees

.GroupBy(e => e.Salary)

.Where(g => g.Count() > 1)

.SelectMany(g => g);

Permalink

LINQ LINQ Tutorial · LINQ

How to safely use First() with fallback

var emp = employees.FirstOrDefault(e => e.Name == "Unknown") ?? new

Employee { Name = "Default" };

Permalink

LINQ LINQ Tutorial · LINQ

Replace foreach with LINQ

employees.ForEach(e => Console.WriteLine(e.Name));

Follow :

✅ This is not LINQ but syntactic sugar with List<T>.ForEach.

Permalink

LINQ LINQ Tutorial · LINQ

Convert list to dictionary with name as key

var dict = employees.ToDictionary(e => e.Name, e => e);

Permalink

LINQ LINQ Tutorial · LINQ

Left join with fallback message

var join = from d in departments

join e in employees on d.Name equals e.Department into g

from emp in g.DefaultIfEmpty()

select new {

Department = d.Name,

Employee = emp?.Name ?? "No employee"

Permalink

LINQ LINQ Tutorial · LINQ

Get 3rd highest salary using LINQ

var third = employees

.OrderByDescending(e => e.Salary)

.Skip(2)

.FirstOrDefault();

Permalink

LINQ LINQ Tutorial · LINQ

LINQ query to convert names to uppercase

var upper = employees.Select(e => e.Name.ToUpper());

🏁 Final Set (Q101–Q111)

Permalink

LINQ LINQ Tutorial · LINQ

Extract names and first letters

var result = employees.Select(e => new { e.Name, FirstLetter =

e.Name[0] });

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Partition employees based on salary threshold

var high = employees.Where(e => e.Salary >= 80000);

var low = employees.Where(e => e.Salary < 80000);

Permalink

LINQ LINQ Tutorial · LINQ

Check if department exists in list

bool exists = departments.Any(d => d.Name == "Marketing");

Permalink

LINQ LINQ Tutorial · LINQ

Select anonymous object with calculated tax

var taxed = employees.Select(e => new {

e.Name,

Tax = e.Salary * 0.1

});

Permalink

LINQ LINQ Tutorial · LINQ

Get distinct list of department names

var deptNames = employees.Select(e => e.Department).Distinct();

Permalink

LINQ LINQ Tutorial · LINQ

Generate custom formatted strings

var display = employees.Select(e => $"{e.Name} earns ₹{e.Salary}");

Permalink

LINQ LINQ Tutorial · LINQ

Group and sort within group

var groupSort = employees

.GroupBy(e => e.Department)

.Select(g => new {

Dept = g.Key,

Emp = g.OrderBy(e => e.Name)

});

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

Compare two lists of employees

bool same = list1.Select(e => e.Id).SequenceEqual(list2.Select(e =>

e.Id));

Permalink

LINQ LINQ Tutorial · LINQ

Filter employees with salary in specific set

var filterSalaries = new[] { 60000, 80000 };

var match = employees.Where(e => filterSalaries.Contains(e.Salary));

Permalink

LINQ LINQ Tutorial · LINQ

Convert to dictionary with Id and Name

var idNameDict = employees.ToDictionary(e => e.Id, e => e.Name);

Permalink

LINQ LINQ Tutorial · LINQ

Replace empty departments with “Unassigned”

var updated = employees.Select(e => new {

e.Name,

Department = string.IsNullOrEmpty(e.Department) ? "Unassigned" :

e.Department

});

Permalink

LINQ LINQ Tutorial · LINQ

How to perform a cross join with LINQ?

var crossJoin = from e in employees

from d in departments

select new { Employee = e.Name, Department = d.Name

Explanation:

Cross join pairs every employee with every department. Useful for generating all

combinations, e.g., for testing or creating matrices.

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ to XML to query XML data?

using System.Xml.Linq;

string xml = @"<Employees>

<Employee Id='1'><Name>Alice</Name></Employee>

<Employee Id='2'><Name>Bob</Name></Employee>

</Employees>";

XDocument doc = XDocument.Parse(xml);

var names = doc.Descendants("Employee")

.Select(x => x.Element("Name")?.Value);

foreach (var name in names)

Console.WriteLine(name);

Explanation:

LINQ to XML provides an elegant way to query and manipulate XML data as objects.

Permalink

LINQ LINQ Tutorial · LINQ

How to perform a left outer join in LINQ?

var leftJoin = from d in departments

join e in employees on d.Name equals e.Department

into empGroup

from emp in empGroup.DefaultIfEmpty()

select new { Department = d.Name, EmployeeName =

emp?.Name ?? "No Employee" };

Explanation:

Returns all departments with matching employees or “No Employee” if none exist.

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ with asynchronous streams?

using System.Threading.Tasks;

using System.Linq;

using System.Collections.Generic;

Follow :

async IAsyncEnumerable<int> GenerateNumbersAsync()

for (int i = 1; i <= 5; i++)

await Task.Delay(100);

yield return i;

async Task ExampleAsync()

await foreach (var number in GenerateNumbersAsync().Where(n => n

% 2 == 0))

Console.WriteLine(number);

Explanation:

Combine LINQ with asynchronous streams to filter async data efficiently.

Permalink

LINQ LINQ Tutorial · LINQ

How to query JSON data using LINQ?

using System.Text.Json;

using System.Text.Json.Nodes;

string json =

@"[{""Name"":""Alice"",""Age"":30},{""Name"":""Bob"",""Age"":25}]";

JsonArray arr = JsonNode.Parse(json).AsArray();

var names = arr.Select(node => node["Name"].GetValue<string>());

foreach (var name in names)

Console.WriteLine(name);

Follow :

Explanation:

Use System.Text.Json to parse JSON, then LINQ to query its nodes.

Permalink

LINQ LINQ Tutorial · LINQ

How to filter distinct objects by a property?

var distinctByDept = employees

.GroupBy(e => e.Department)

.Select(g => g.First());

Explanation:

Groups employees by department and selects one employee from each group to get distinct

departments.

Permalink

LINQ LINQ Tutorial · LINQ

How to calculate running totals using LINQ?

var salaries = employees.Select(e => e.Salary).ToList();

double runningTotal = 0;

var runningTotals = salaries.Select(s => runningTotal += s);

foreach (var total in runningTotals)

Console.WriteLine(total);

Explanation:

Accumulates sums as you iterate through the sequence.

Permalink

LINQ LINQ Tutorial · LINQ

How to perform conditional LINQ queries?

string searchName = "Alice";

var query = employees.AsQueryable();

if (!string.IsNullOrEmpty(searchName))

query = query.Where(e => e.Name.Contains(searchName));

var result = query.ToList();

Follow :

Explanation:

Build LINQ queries dynamically based on conditions.

Permalink

LINQ LINQ Tutorial · LINQ

How to flatten hierarchical data with SelectMany?

var departmentsWithEmployees = new[]

new { Department = "IT", Employees = new [] {"Bob", "Charlie"}

new { Department = "HR", Employees = new [] {"Alice", "Eva"} }

var allEmployees = departmentsWithEmployees

.SelectMany(d => d.Employees);

foreach (var emp in allEmployees)

Console.WriteLine(emp);

Explanation:

SelectMany flattens nested collections into a single sequence.

Permalink

LINQ LINQ Tutorial · LINQ

How to group join with multiple collections?

var groupJoin = from d in departments

join e in employees on d.Name equals e.Department

into empGroup

select new { Department = d.Name, Employees =

empGroup };

foreach (var group in groupJoin)

Console.WriteLine($"{group.Department}:");

foreach (var emp in group.Employees)

Console.WriteLine($" - {emp.Name}");

Follow :

Explanation:

Groups employees under their respective departments.

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ for paging data?

int pageNumber = 2;

int pageSize = 2;

var page = employees

.OrderBy(e => e.Id)

.Skip((pageNumber - 1) * pageSize)

.Take(pageSize);

Explanation:

Retrieve specific pages from data sets (useful for UI pagination).

Permalink

LINQ LINQ Tutorial · LINQ

How to find max salary per department?

var maxSalaryPerDept = employees

.GroupBy(e => e.Department)

.Select(g => new { Department = g.Key, MaxSalary = g.Max(e =>

e.Salary) });

Permalink

LINQ LINQ Tutorial · LINQ

How to check sequence equality ignoring order?

bool areEqual = employees.Select(e => e.Id).OrderBy(id => id)

.SequenceEqual(anotherList.Select(e => e.Id).OrderBy(id => id));

Permalink

LINQ LINQ Tutorial · LINQ

How to get distinct by multiple properties?

var distinctByDeptAndSalary = employees

.GroupBy(e => new { e.Department, e.Salary })

.Select(g => g.First());

Permalink

LINQ LINQ Tutorial · LINQ

How to implement pagination with total count using LINQ?

int pageNumber = 1;

Follow :

int pageSize = 3;

var totalCount = employees.Count();

var pageData = employees

.OrderBy(e => e.Id)

.Skip((pageNumber - 1) * pageSize)

.Take(pageSize)

.ToList();

Console.WriteLine($"Total Employees: {totalCount}");

foreach(var emp in pageData)

Console.WriteLine($"{emp.Name} - {emp.Department}");

Explanation:

You get total count separately and then take the required page using Skip and Take.

Permalink

LINQ LINQ Tutorial · LINQ

How to check if two sequences have the same elements

regardless of order and duplicates?

var list1 = new[] {1, 2, 3, 4};

var list2 = new[] {4, 3, 2, 1};

bool areEqual = !list1.Except(list2).Any() &&

!list2.Except(list1).Any();

Console.WriteLine(areEqual); // Output: True

Explanation:

This checks if both lists contain the same elements, ignoring order and duplicates.

Permalink

LINQ LINQ Tutorial · LINQ

How to create a dictionary from a list with duplicate keys?

var dict = employees

.GroupBy(e => e.Department)

.ToDictionary(g => g.Key, g => g.ToList());

Follow :

foreach (var kvp in dict)

Console.WriteLine($"{kvp.Key} Department:");

foreach (var emp in kvp.Value)

Console.WriteLine($" - {emp.Name}");

Explanation:

Group employees by department and convert groups to dictionary entries.

Permalink

LINQ LINQ Tutorial · LINQ

How to perform union of two collections without duplicates?

var list1 = new[] { "Alice", "Bob", "Charlie" };

var list2 = new[] { "Bob", "David", "Eva" };

var union = list1.Union(list2);

foreach (var name in union)

Console.WriteLine(name);

Explanation:

Union returns distinct elements from both collections.

Permalink

LINQ LINQ Tutorial · LINQ

How to perform intersection of two collections?

var intersect = list1.Intersect(list2);

foreach (var name in intersect)

Console.WriteLine(name); // Output: Bob

Permalink

LINQ LINQ Tutorial · LINQ

How to find elements present in the first but not in the second

list?

var except = list1.Except(list2);

foreach (var name in except)

Follow :

Console.WriteLine(name); // Output: Alice, Charlie

Permalink

LINQ LINQ Tutorial · LINQ

How to find employees with salary between a range?

var midRange = employees.Where(e => e.Salary >= 65000 && e.Salary <=

85000);

foreach(var emp in midRange)

Console.WriteLine($"{emp.Name} - {emp.Salary}");

Permalink

LINQ LINQ Tutorial · LINQ

How to group and order groups by count descending?

var groupOrder = employees

.GroupBy(e => e.Department)

.OrderByDescending(g => g.Count());

foreach (var group in groupOrder)

Console.WriteLine($"{group.Key} has {group.Count()} employees");

Permalink

LINQ LINQ Tutorial · LINQ

How to check if sequence contains a specific element?

bool containsAlice = employees.Any(e => e.Name == "Alice");

Permalink

LINQ LINQ Tutorial · LINQ

How to sum salaries of employees in a department?

var totalSalaryHR = employees

.Where(e => e.Department == "HR")

.Sum(e => e.Salary);

Console.WriteLine($"Total salary in HR: {totalSalaryHR}");

Permalink

LINQ LINQ Tutorial · LINQ

How to get employee with maximum salary in a department?

var maxSalaryInIT = employees

.Where(e => e.Department == "IT")

Follow :

.OrderByDescending(e => e.Salary)

.FirstOrDefault();

Console.WriteLine($"{maxSalaryInIT?.Name} has the highest salary in

IT");

Permalink

LINQ LINQ Tutorial · LINQ

How to safely get first element or a default?

var unknownEmployee = employees

.FirstOrDefault(e => e.Name == "Unknown") ?? new Employee { Name

= "Default Employee" };

Permalink

LINQ LINQ Tutorial · LINQ

How to concatenate two sequences?

var list3 = new[] { "Frank", "Grace" };

var concatenated = list1.Concat(list3);

foreach(var name in concatenated)

Console.WriteLine(name);

Permalink

LINQ LINQ Tutorial · LINQ

How to group by multiple keys?

var groupedMulti = employees

.GroupBy(e => new { e.Department, SalaryLevel = e.Salary > 75000

? "High" : "Low" });

foreach (var group in groupedMulti)

Console.WriteLine($"{group.Key.Department} -

{group.Key.SalaryLevel} ({group.Count()} employees)");

Permalink

LINQ LINQ Tutorial · LINQ

How to calculate average salary per department?

var avgSalaryByDept = employees

.GroupBy(e => e.Department)

Follow :

.Select(g => new { Department = g.Key, AverageSalary =

g.Average(e => e.Salary) });

foreach (var dept in avgSalaryByDept)

Console.WriteLine($"{dept.Department}: {dept.AverageSalary}");

Permalink

LINQ LINQ Tutorial · LINQ

How to find the top N highest paid employees?

int topN = 3;

var topEarners = employees

.OrderByDescending(e => e.Salary)

.Take(topN);

foreach (var emp in topEarners)

Console.WriteLine($"{emp.Name}: {emp.Salary}");

Explanation:

Orders employees by salary descending and takes the top N.

Permalink

LINQ LINQ Tutorial · LINQ

How to find employees whose names start and end with the same

letter?

var filtered = employees

.Where(e => e.Name.StartsWith(e.Name.Last().ToString(),

StringComparison.OrdinalIgnoreCase));

foreach (var emp in filtered)

Console.WriteLine(emp.Name);

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ to find the most common first letter of employee

names?

var mostCommonLetter = employees

.GroupBy(e => e.Name[0])

.OrderByDescending(g => g.Count())

.FirstOrDefault()?.Key;

Console.WriteLine($"Most common first letter: {mostCommonLetter}");

Follow :

Permalink

LINQ LINQ Tutorial · LINQ

How to create a lookup and use it for quick searches?

var lookup = employees.ToLookup(e => e.Department);

var itEmployees = lookup["IT"];

foreach (var emp in itEmployees)

Console.WriteLine(emp.Name);

Explanation:

Lookup is like a dictionary but allows multiple values per key.

Permalink

LINQ LINQ Tutorial · LINQ

How to group employees by salary ranges dynamically?

var salaryRanges = employees.GroupBy(e =>

if (e.Salary < 50000) return "Low";

else if (e.Salary <= 80000) return "Medium";

else return "High";

});

foreach (var group in salaryRanges)

Console.WriteLine($"{group.Key} Salary Range:");

foreach (var emp in group)

Console.WriteLine($" - {emp.Name} ({emp.Salary})");

Permalink

LINQ LINQ Tutorial · LINQ

How to flatten a dictionary of lists into a single sequence?

var dict = new Dictionary<string, List<string>>

{"IT", new List<string> {"Bob", "Alice"}},

{"HR", new List<string> {"Eva", "John"}}

Follow :

var allEmployees = dict.SelectMany(kvp => kvp.Value);

foreach (var name in allEmployees)

Console.WriteLine(name);

Permalink

LINQ LINQ Tutorial · LINQ

How to check if a collection is empty with LINQ?

bool hasEmployees = employees.Any();

Console.WriteLine(hasEmployees ? "There are employees" : "No

employees");

Permalink

LINQ LINQ Tutorial · LINQ

How to reverse a sequence using LINQ?

var reversed = employees.Select(e => e.Name).Reverse();

foreach (var name in reversed)

Console.WriteLine(name);

Permalink

LINQ LINQ Tutorial · LINQ

How to perform a distinct with a custom comparer?

class EmployeeNameComparer : IEqualityComparer<Employee>

public bool Equals(Employee x, Employee y) => x.Name == y.Name;

public int GetHashCode(Employee obj) => obj.Name.GetHashCode();

var distinctByName = employees.Distinct(new EmployeeNameComparer());

foreach (var emp in distinctByName)

Console.WriteLine(emp.Name);

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ to check if all employees belong to a

department?

Follow :

bool allInIT = employees.All(e => e.Department == "IT");

Console.WriteLine(allInIT ? "All employees are in IT" : "Not all

employees are in IT");

Permalink

LINQ LINQ Tutorial · LINQ

How to select a property and transform it?

var employeeEmails = employees.Select(e => e.Name.ToLower() +

"@company.com");

foreach (var email in employeeEmails)

Console.WriteLine(email);

Permalink

LINQ LINQ Tutorial · LINQ

How to concatenate two sequences with a separator?

var seq1 = new[] { "Alice", "Bob" };

var seq2 = new[] { "Charlie", "David" };

var concatenated = se

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ to find employees with duplicate names?

var duplicates = employees

.GroupBy(e => e.Name)

.Where(g => g.Count() > 1)

.Select(g => g.Key);

foreach (var name in duplicates)

Console.WriteLine(name);

Permalink

LINQ LINQ Tutorial · LINQ

How to use LINQ to paginate and return total pages?

int pageSize = 2;

Follow :

int totalItems = employees.Count();

int totalPages = (int)Math.Ceiling(totalItems / (double)pageSize);

Console.WriteLine($"Total Pages: {totalPages}");

int pageNumber = 2;

var pageData = employees

.Skip((pageNumber - 1) * pageSize)

.Take(pageSize);

foreach (var emp in pageData)

Console.WriteLine(emp.Name);

Permalink

LINQ LINQ Tutorial · LINQ

How to join strings in LINQ?

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

string joined = string.Join(", ", names);

Console.WriteLine(joined);

Follow :

Permalink