LINQ interviews reward understanding the machinery, not just the syntax — why IQueryable exists separately from IEnumerable, what deferred execution actually defers, how a LINQ-to-SQL query ends up as SQL at all. This covers the full range, from the basics through expression trees and PLINQ, with code, a couple of diagrams, and a mock test at the end.
LINQ Fundamentals
Q1. What is LINQ and why is it useful?
LINQ (Language Integrated Query) is a set of C# language features and BCL methods that let you write queries — filtering, projecting, sorting, grouping — directly in C#, against any data source that implements the right interface (in-memory collections, SQL databases, XML, and more), instead of a different query API for each source. The payoff is one consistent, compile-time-checked query syntax everywhere, rather than string-based SQL in one place and manual loops in another.
Q2. What are the three main components of LINQ?
| Component | Role |
|---|---|
| Standard Query Operators | The Where/Select/OrderBy/etc. extension methods themselves |
| Language extensions | Query syntax (from...where...select) and lambda expressions the compiler understands |
| LINQ providers | The translation layer for a specific source — LINQ to Objects, LINQ to SQL, LINQ to XML, EF Core's provider, etc. |
Q3. Can you explain the difference between LINQ to Objects, LINQ to SQL, and LINQ to XML?
| LINQ to Objects | LINQ to SQL | LINQ to XML | |
|---|---|---|---|
| Queries | In-memory IEnumerable<T> collections | A SQL Server database (via a lightweight ORM) | XDocument/XElement trees |
| Execution | Runs as plain C# in the CLR | Translated into SQL, run by the database | Runs as plain C# over the loaded XML |
| Status today | Still current and heavily used | Largely superseded by EF Core for new projects | Still current for XML manipulation |
Q4. What is a Lambda Expression in LINQ?
var adults = people.Where(p => p.Age >= 18);
// ^^^^^^^^^^^^^^^^^ a lambda expressionA lambda is an inline, unnamed function — (parameters) => expression — used everywhere in LINQ as the predicate/selector passed to query operators. It's the concise alternative to writing out a full named method just to pass as a delegate.
Q5. How do LINQ queries differ from traditional loop and conditional statements?
// Traditional loop
var result = new List<Person>();
foreach (var p in people)
{
if (p.Age >= 18) result.Add(p);
}
// LINQ — declarative, same outcome
var result = people.Where(p => p.Age >= 18).ToList();A loop is imperative — you spell out exactly how to build the result step by step. LINQ is declarative — you describe what you want, and the operator implementation handles the how. The LINQ version is also composable: chaining another .OrderBy() or .Select() is one more method call, not a restructured loop body.
Q6. What is the purpose of the IEnumerable interface in LINQ?
IEnumerable<T> is the minimal contract for "something you can iterate over" — a single GetEnumerator() method. Virtually every LINQ to Objects extension method is defined as an extension on IEnumerable<T>, which is exactly why LINQ works uniformly across arrays, List<T>, Dictionary<T>, and any custom type that implements it.
Q7. How does LINQ use deferred execution?
var query = numbers.Where(n => n > 10); // nothing has run yet
numbers.Add(15); // this WILL be included below
foreach (var n in query) { ... } // execution actually happens HEREMost LINQ operators build up a description of the query without running it — the actual filtering/projecting only happens when the result is enumerated (a foreach, ToList(), a single-value operator like First()). This is why a query variable can be defined once and re-run later against the data source's current state, as the example above shows.
Q8. What is the difference between IEnumerable and IQueryable?
| IEnumerable<T> | IQueryable<T> | |
|---|---|---|
| Execution location | In the CLR, in-memory | Translated and executed by the underlying provider (e.g. a database) |
| Represents | A realized (or lazily-produced) sequence of values | An expression tree describing a not-yet-executed query |
| Filtering location | After data is already loaded into memory | Pushed down — e.g. becomes a SQL WHERE clause |
| Typical source | Lists, arrays, LINQ to Objects | EF Core DbSet<T>, LINQ to SQL |
This distinction is one of the most-tested LINQ concepts precisely because getting it wrong is expensive: calling .Where() on an IQueryable<T> becomes part of the SQL sent to the database; calling .AsEnumerable() first and then .Where() pulls every row into memory and filters there instead — the query still runs, just far less efficiently.
Q9. Give an example of a simple LINQ query that selects items from a collection.
// Method syntax
var names = people.Where(p => p.Age > 18).Select(p => p.Name);
// Query syntax — equivalent
var names = from p in people
where p.Age > 18
select p.Name;Q10. Explain the role of Extension Methods in LINQ.
Extension methods are what let Where/Select/OrderBy be called as if they were instance methods on any IEnumerable<T> (or IQueryable<T>), even though they're defined as static methods elsewhere — this is the exact mechanism that lets LINQ add query capability to types (arrays, List<T>) without modifying those types at all.
LINQ to Objects
Q11. What are the benefits of using LINQ to Objects?
Concise, readable, composable queries over in-memory collections; type safety and IntelliSense the compiler checks at build time (versus a hand-rolled loop with easy off-by-one bugs); and a consistent API whether you're filtering a List<int> or a Dictionary<string, Order>.
Q12. Can you show how to filter a list of items using the Where operator?
var expensiveProducts = products.Where(p => p.Price > 100).ToList();Q13. What is the purpose of the Select clause in LINQ?
var names = products.Select(p => p.Name);
// Projecting into a new shape entirely:
var summaries = products.Select(p => new { p.Name, IsExpensive = p.Price > 100 });Select projects each element into a new form — extracting one property, or building an entirely new shape (anonymous type or a DTO) from the source elements. It's the standard way to shape a query's output independently from what the source data actually looks like.
Q14. How do you sort data with LINQ?
var sorted = people
.OrderBy(p => p.LastName)
.ThenBy(p => p.FirstName);
var sortedDesc = people.OrderByDescending(p => p.Age);Q15. Explain how the GroupBy method works in LINQ.
var byDepartment = employees.GroupBy(e => e.Department);
foreach (var group in byDepartment)
{
Console.WriteLine($"{group.Key}: {group.Count()} employees");
}GroupBy partitions a sequence into groups sharing a common key, returning a sequence of IGrouping<TKey, TElement> — each group carries its Key plus the matching elements, so you can enumerate or aggregate within each group without a separate manual bucketing step.
Q16. What is the difference between the First and FirstOrDefault methods?
| First() | FirstOrDefault() | |
|---|---|---|
| No match found | Throws InvalidOperationException | Returns default(T) — null for reference types, 0 for int, etc. |
| Use when | A missing match is genuinely an unexpected/exceptional case | A missing match is a normal, expected outcome to handle |
Q17. How would you join two collections using LINQ?
var query = orders.Join(
customers,
order => order.CustomerId,
customer => customer.Id,
(order, customer) => new { order.Id, customer.Name }
);
// Query syntax:
var query = from o in orders
join c in customers on o.CustomerId equals c.Id
select new { o.Id, c.Name };Q18. What are projection operations in LINQ?
Select (one output per input element) and SelectMany (flattening a sequence of sequences into one flat sequence) are the two projection operators — SelectMany is what you reach for when each element itself produces a collection (e.g. each Order has a list of OrderItems) and you want one flat sequence of all the items across every order.
Q19. How can you convert an array into a list using LINQ?
int[] array = { 1, 2, 3 };
List<int> list = array.ToList();Q20. What is the OfType method in LINQ?
object[] items = { 1, "two", 3, "four" };
var strings = items.OfType<string>(); // { "two", "four" }OfType<T>() filters a sequence down to only the elements that are (or can be cast to) a given type — useful for a mixed-type collection where you only want to work with one specific type, silently skipping everything else instead of throwing on a failed cast.
LINQ to SQL and Databases
Q21. What is LINQ to SQL?
LINQ to SQL is Microsoft's original lightweight ORM (shipped with .NET 3.5) mapping C# classes to SQL Server tables and translating LINQ queries into SQL — it only ever supported SQL Server specifically, which is the main reason Entity Framework (and later EF Core, provider-agnostic across many databases) became the standard choice for new projects instead.
Q22. Explain how LINQ to SQL interacts with a relational database.
From a LINQ query to a result set
LINQ query
Written as C# against a DataContext
Expression Tree
The query is captured as data, not executed yet
SQL translation
The provider converts the tree into a SQL statement
Database execution
SQL Server runs it, returns rows
Materialization
Rows are mapped back into C# objects
Q23. What is an ORM (Object-Relational Mapper) in the context of LINQ to SQL?
An ORM maps database tables to classes and rows to object instances, letting you work with plain C# objects and LINQ queries instead of hand-written SQL and manual result-set-to-object mapping — LINQ to SQL was Microsoft's first mainstream ORM to expose that mapping through LINQ specifically, rather than a separate query API.
Q24. Can you demonstrate a simple LINQ to SQL query that selects data from a single table?
using (var db = new MyDataContext())
{
var activeCustomers = db.Customers
.Where(c => c.IsActive)
.ToList();
}Q25. How do you perform an inner join using LINQ to SQL?
var query = from o in db.Orders
join c in db.Customers on o.CustomerId equals c.Id
select new { o.Id, c.Name };
// Translates to a SQL INNER JOIN, executed by SQL ServerQ26. Describe the process of performing an insert operation with LINQ to SQL.
var customer = new Customer { Name = "Ada Lovelace" };
db.Customers.InsertOnSubmit(customer);
db.SubmitChanges();Q27. How is data updated in the database using LINQ to SQL?
var customer = db.Customers.Single(c => c.Id == 5);
customer.Name = "Updated Name";
db.SubmitChanges(); // the DataContext tracked the change automaticallyQ28. Explain how to delete a record from a database using LINQ to SQL.
var customer = db.Customers.Single(c => c.Id == 5);
db.Customers.DeleteOnSubmit(customer);
db.SubmitChanges();Q29. What are Data Context classes in LINQ to SQL?
A DataContext is LINQ to SQL's equivalent of EF Core's DbContext — it represents the database connection, tracks changes to loaded entities, and turns SubmitChanges() into the actual INSERT/UPDATE/DELETE statements, and its Table<T> properties are the queryable entry points analogous to DbSet<T>.
Q30. How do you handle transactions in LINQ to SQL?
using (var scope = new TransactionScope())
{
db.Customers.InsertOnSubmit(customer);
db.SubmitChanges();
db.Orders.InsertOnSubmit(order);
db.SubmitChanges();
scope.Complete();
}LINQ to XML
Q31. What is LINQ to XML and what are its advantages?
LINQ to XML (System.Xml.Linq) is an in-memory XML API — XDocument/XElement — queryable and constructible with the same LINQ operators as any other in-memory collection. Its advantage over the older XmlDocument/DOM API is exactly that: querying XML with Where/Select instead of verbose XPath or manual node-walking.
Q32. How do you create an XML document using LINQ to XML?
var doc = new XDocument(
new XElement("Customers",
new XElement("Customer",
new XAttribute("id", 1),
new XElement("Name", "Ada Lovelace")
)
)
);Q33. Describe how to read data from an XML document using LINQ.
var doc = XDocument.Load("customers.xml");
var names = doc.Descendants("Customer")
.Select(c => c.Element("Name")?.Value);Q34. How do you query XML elements and attributes with LINQ?
var activeCustomers = doc.Descendants("Customer")
.Where(c => (bool)c.Attribute("active"));Q35. What is the XDocument class and how is it used?
XDocument represents an entire XML document (including things like the XML declaration) and is the typical root object you load/save/construct — XElement represents just one element and its subtree, usable standalone when you don't need the full document wrapper.
Q36. Explain the process of transforming XML with LINQ to XML.
var transformed = new XElement("People",
doc.Descendants("Customer").Select(c =>
new XElement("Person", c.Element("Name")?.Value)
)
);Since LINQ to XML is just LINQ over objects, transformation is really just a Select projecting old elements into a new shape — the same functional query pattern used everywhere else in LINQ, applied to constructing new XML instead of filtering a list.
Q37. How can you validate XML against an XSD schema in LINQ to XML?
var schemas = new XmlSchemaSet();
schemas.Add("", "customers.xsd");
bool isValid = true;
doc.Validate(schemas, (o, e) => isValid = false);Q38. Describe the differences between the XElement and XAttribute classes.
| XElement | XAttribute | |
|---|---|---|
| Represents | An XML element (can contain child elements/text) | A name/value pair on an element |
| Nesting | Can contain other XElements | Cannot contain anything — always a leaf |
Q39. How would you remove nodes from an XML document using LINQ to XML?
doc.Descendants("Customer")
.Where(c => (bool)c.Attribute("inactive"))
.Remove();Q40. Discuss the process of serializing and deserializing XML data using LINQ to XML.
LINQ to XML itself is really just for building/querying the XML tree directly — full object↔XML serialization is more commonly handled by XmlSerializer or DataContractSerializer, with LINQ to XML stepping in when you need to hand-construct or query XML shapes that don't map cleanly to a serializable class.
Advanced LINQ Query Expressions
Q41. What is a complex query in LINQ, and can you provide an example?
var result = orders
.Where(o => o.Status == "Completed")
.GroupBy(o => o.CustomerId)
.Select(g => new
{
CustomerId = g.Key,
TotalSpent = g.Sum(o => o.Total),
OrderCount = g.Count()
})
.Where(x => x.TotalSpent > 1000)
.OrderByDescending(x => x.TotalSpent);A "complex" LINQ query is just several operators chained together — filter, then group, then aggregate per group, then filter the aggregated results, then sort. Each step is simple in isolation; the complexity is entirely in the composition, which is exactly what makes LINQ readable even for a multi-step transformation like this.
Q42. How do you perform subqueries in LINQ?
var customersWithOrders = customers.Where(c =>
orders.Any(o => o.CustomerId == c.Id)
);A LINQ subquery is just a LINQ query used as part of a larger query's predicate/projection — here, Any() runs as an inner check for each outer customer. Against a database provider, this correctly translates into a SQL subquery/EXISTS, not a separate round trip per customer.
Q43. Explain the use of the let keyword in LINQ queries.
var query = from p in products
let discountedPrice = p.Price * 0.9m
where discountedPrice > 50
select new { p.Name, discountedPrice };let introduces a named intermediate value inside a query-syntax expression, so a computed value can be reused (in a where clause and the select projection, as above) without recalculating it or breaking the query into separate steps.
Q44. What is the difference between ConcurrentBag and IList when used with LINQ queries?
| IList<T> | ConcurrentBag<T> | |
|---|---|---|
| Thread safety | Not thread-safe for concurrent writes | Thread-safe — designed for concurrent add/take |
| Order | Preserves insertion order | No guaranteed order |
| Typical LINQ use | The default choice for sequential queries | Collecting results from parallel work (e.g. PLINQ) safely |
Q45. How does the Any method work and what is a scenario where it can be used?
bool hasOverdueInvoices = invoices.Any(i => i.DueDate < DateTime.Today);
bool hasAny = invoices.Any(); // just checks for at least one elementAny() returns true the moment it finds one matching element, without evaluating the rest of the sequence — the correct, short-circuiting way to check "does at least one match exist" instead of Count(predicate) > 0, which pointlessly counts every match before comparing.
Q46. What are set operations in LINQ and how do you use them?
| Operator | Returns |
|---|---|
| Distinct() | Unique elements, duplicates removed |
| Union() | All elements from both sequences, duplicates removed |
| Intersect() | Elements present in both sequences |
| Except() | Elements in the first sequence but not the second |
Q47. Can you use custom functions in LINQ queries? If so, how?
bool IsPremiumCustomer(Customer c) => c.TotalSpent > 10000;
var premium = customers.Where(c => IsPremiumCustomer(c));Any method (a local function, a static helper, an instance method) can be referenced inside a LINQ to Objects lambda since it all just executes as normal C# in the CLR. Against a database provider (LINQ to SQL/EF Core), custom methods generally can't be translated into SQL unless the provider specifically recognizes them — this is a common source of a runtime "could not be translated" exception.
Q48. How would you perform pagination of data with LINQ?
int page = 3, pageSize = 20;
var pageOfResults = query
.OrderBy(x => x.Id) // always order before paging
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();Q49. Describe how to implement a full-text search with LINQ.
var results = products.Where(p =>
p.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)
);For LINQ to Objects, this is just a Contains() check. Against a real full-text search need at database scale, LINQ to Objects/EF Core's Contains() typically translates to a SQL LIKE '%term%', which can't use a standard index efficiently — a genuine full-text search workload usually needs the database's own full-text index feature (or an external engine like Elasticsearch) instead.
Q50. What is the role of expression trees in LINQ?
Expression<Func<Product, bool>> predicate = p => p.Price > 100;
// predicate.Body, predicate.Parameters — the query is DATA, not compiled codeAn expression tree represents code as an inspectable data structure rather than compiled, directly executable IL — this is exactly what lets a provider like EF Core look at a LINQ query's structure and translate it into SQL, instead of just running it as C#. IQueryable<T> is built entirely on Expression<TDelegate> for this reason; IEnumerable<T>'s LINQ operators just take plain delegates (Func<T>), which can only ever run, never be inspected and translated.
LINQ Query Optimization and Performance
Q51. What factors can impact the performance of a LINQ query?
- Whether filtering happens in the database (IQueryable pushed down) or after loading everything into memory (accidentally forced to IEnumerable too early)
- Multiple enumeration of the same deferred query, silently re-running the whole pipeline each time
- N+1 query patterns from lazy-loaded navigation properties accessed inside a loop
- Unnecessary ToList()/ToArray() materializing intermediate results that didn't need to exist
Q52. How can you optimize a LINQ query that processes a large amount of data?
// Filter and project in the database, not after loading everything:
var names = db.Customers
.Where(c => c.IsActive)
.Select(c => c.Name) // only pulls the Name column, not the whole row
.ToList();Push as much filtering and projection as possible into the IQueryable chain before it ever materializes, so the database (not your application's memory) does the heavy lifting — and only select the columns you actually need, rather than loading full entities just to read one property.
Q53. Explain the effects of deferred versus immediate execution.
| Deferred | Immediate | |
|---|---|---|
| Examples | Where, Select, OrderBy | ToList, ToArray, Count, First, Sum |
| When it runs | On enumeration (foreach, or a later immediate call) | Right when the method is called |
| Risk | Re-running the whole query if enumerated multiple times | Snapshotting results — won't reflect later source changes |
Q54. When should you use the ToList or ToArray methods?
Call one when you need to materialize the results once and reuse them multiple times without re-running the query each time, or when you need to detach the result from a source that might change/be disposed (like a DbContext) before you're done using the data.
Q55. What issues might arise from unnecessarily chaining LINQ operators?
// Inefficient — three full passes over the sequence
var result = items.Where(x => x.IsActive).Select(x => x.Name).OrderBy(x => x).ToList();
// Same result, same passes really — chaining itself isn't the problem;
// the real risk is re-enumerating an un-materialized query multiple times:
var query = items.Where(x => x.IsActive);
var count = query.Count(); // runs the query
var list = query.ToList(); // runs the ENTIRE query again from scratchChaining operators isn't inherently wasteful — LINQ to Objects streams elements through the chain lazily rather than materializing an array after each step. The real performance trap is re-enumerating a deferred query multiple times (as above), which silently reruns the whole pipeline (or, against a database, issues the query again) each time.
Q56. How does LINQ query optimization differ in LINQ to Objects vs. LINQ to SQL?
LINQ to Objects optimization is about algorithmic efficiency and avoiding redundant enumeration in your own process's memory. LINQ to SQL/EF Core optimization is about what SQL actually gets generated — indexing the columns your WHERE/JOIN/ORDER BY translate to, avoiding N+1 query patterns, and using .AsNoTracking() for read-only queries to skip EF's change-tracking overhead entirely.
Q57. What considerations should you make when combining LINQ with parallel programming?
PLINQ (.AsParallel()) only helps for CPU-bound work with enough data to justify the partitioning/coordination overhead — for small collections or I/O-bound work, the overhead can make it slower than sequential LINQ. Also watch for thread-safety in any side-effecting lambda passed to a parallel query; a lambda that mutates shared state needs its own synchronization, which PLINQ doesn't provide for you.
Q58. How do you profile LINQ queries to monitor performance?
- For EF Core: enable logging (or MiniProfiler/EF Core's own logging) to see the actual generated SQL, and check it against an EXPLAIN plan
- For LINQ to Objects: a standard .NET profiler (dotnet-trace, Visual Studio Profiler) to see where time is actually spent in a query chain
- Watch specifically for repeated identical database round trips — the classic N+1 signature
LINQ Exception Handling and Debugging
Q59. How do you handle exceptions in LINQ queries?
try
{
var result = items.Select(x => 100 / x.Divisor).ToList();
}
catch (DivideByZeroException ex)
{
// handle it
}Because of deferred execution, an exception thrown inside a lambda doesn't surface at the line where the query was defined — it surfaces at the line where the query is actually enumerated (a foreach, ToList(), etc.), which can be confusingly far from where the problematic lambda was written.
Q60. What are some common exceptions you may encounter when using LINQ and how do you resolve them?
| Exception | Common cause |
|---|---|
| InvalidOperationException | First()/Single() finding zero (or, for Single, more than one) matching elements |
| ArgumentNullException | Passing null where a source or predicate was required |
| NotSupportedException | A LINQ-to-SQL/EF Core provider can't translate part of the query into SQL |
| NullReferenceException | Accessing a member on a null result inside a projection (e.g. an unmatched navigation property) |
Q61. Describe techniques for debugging complex LINQ queries.
- Break a long chain into named intermediate variables so you can inspect each step's result individually
- Use .ToList() temporarily mid-chain during debugging to force and inspect materialization at that point
- For provider-translated queries, log/inspect the generated SQL to see what actually got sent to the database
LINQ and Async Operations
Q62. Can LINQ queries be executed asynchronously? If so, how?
var results = await db.Products
.Where(p => p.Price > 100)
.ToListAsync(); // EF Core's async materializationLINQ to Objects itself has no async operators (it's synchronous CPU work over in-memory data) — the async LINQ methods (ToListAsync, FirstOrDefaultAsync, CountAsync) come from EF Core specifically, letting the actual database round-trip happen without blocking a thread while waiting on I/O.
Q63. Explain how you would stream data from a database using asynchronous LINQ queries.
await foreach (var product in db.Products.AsAsyncEnumerable())
{
Process(product); // each row processed as it arrives, not all buffered first
}Q64. What is IAsyncEnumerable and how does it work with asynchronous streams?
IAsyncEnumerable<T> is the async counterpart to IEnumerable<T> — enumerated with await foreach, it lets a sequence be produced (and consumed) one element at a time asynchronously, which is exactly how EF Core streams query results without materializing the entire result set into memory first.
LINQ Best Practices
Q65. What are some best practices for writing clean and maintainable LINQ queries?
- Prefer method syntax for most queries; query syntax mainly earns its keep for joins/let-heavy queries where it reads better
- Name intermediate variables for genuinely complex, multi-stage queries instead of one giant unreadable chain
- Materialize (ToList/ToArray) deliberately, at the point you actually need concrete results — not reflexively after every query
- Keep predicates simple enough to translate cleanly against a database provider — push complex logic into the query itself, not opaque method calls the provider can't understand
Q66. How do you decide when to use query syntax versus method syntax in LINQ?
| Query syntax | Method syntax | |
|---|---|---|
| Reads well for | Joins, multiple let bindings, SQL-like queries | Everything else — chains of Where/Select/OrderBy |
| Coverage | Doesn't expose every operator (no Sum/Count directly) | Every LINQ operator is available |
| Community convention | Less common in modern C# | The prevailing default style |
Q67. What are some common pitfalls to avoid when using LINQ in large applications?
- Filtering after materializing (.ToList().Where(...)) instead of before, losing the database's ability to push the filter down
- N+1 queries from lazy-loaded navigation properties accessed in a loop
- Re-enumerating a deferred query multiple times without realizing it re-runs each time
- Using .Count() > 0 instead of .Any() for existence checks
Q68. How does the using directive simplify resource management in LINQ?
It's not really LINQ-specific — using ensures a DbContext (or any IDisposable resource a query depends on) is disposed once you're done with it, which matters for LINQ specifically because deferred execution means the context must still be alive at the moment a query is actually enumerated, not just when it was defined.
LINQ and .NET Technologies Integration
Q69. How does LINQ integrate with other .NET technologies like Entity Framework?
EF Core's DbSet<T> implements IQueryable<T>, so every standard LINQ operator works against it directly — EF Core's query provider is what translates the resulting expression tree into SQL, materializes results back into entity objects, and (for tracked queries) hooks into its own change-tracking on the way.
Q70. What role does LINQ play in LINQ to Entities?
"LINQ to Entities" is specifically the name for LINQ queries run against Entity Framework (classic EF6, and by extension EF Core) — LINQ is the query language; Entity Framework is the ORM and provider translating those LINQ queries into database-specific SQL.
Q71. How would you use LINQ with ADO.NET DataSet?
var rows = dataSet.Tables["Customers"].AsEnumerable()
.Where(row => row.Field<bool>("IsActive"))
.Select(row => row.Field<string>("Name"));DataTable.AsEnumerable() (LINQ to DataSet) exposes rows as an IEnumerable<DataRow> so LINQ to Objects operators work over legacy DataSet/DataTable data — useful when integrating LINQ-style querying into an older codebase still built around ADO.NET DataSets rather than a modern ORM.
Q72. Can LINQ be used with MongoDB or other NoSQL databases?
Yes — the official MongoDB .NET driver provides an IMongoQueryable<T> LINQ provider that translates LINQ expressions into MongoDB's query language, and other NoSQL databases/Cosmos DB similarly ship their own LINQ providers — the same expression-tree-translation pattern as LINQ to SQL/EF Core, just targeting a different query language underneath.
LINQ with Various Data Sources
Q73. How do you use LINQ with in-memory collections vs. external data sources?
Syntactically identical — the difference is entirely in the interface: IEnumerable<T> for in-memory collections executes the query as ordinary C#, while IQueryable<T> for external sources builds an expression tree the provider translates into that source's native query language, executed remotely.
Q74. Can LINQ be used to query data from a CSV file? If yes, how?
var rows = File.ReadLines("data.csv")
.Skip(1) // skip the header row
.Select(line => line.Split(','))
.Where(fields => fields[2] == "Active");Read the file into an IEnumerable<string> (one line at a time, lazily, via File.ReadLines) and run ordinary LINQ to Objects operators over it — no special CSV-specific LINQ provider needed for anything beyond basic parsing.
Q75. Explain how LINQ to SharePoint works.
LINQ to SharePoint (via SPMetal-generated entity classes) provides a LINQ provider translating queries into SharePoint's underlying CAML (Collaborative Application Markup Language) query syntax — the same LINQ-to-provider-specific-query-language pattern, targeting SharePoint list data specifically.
Q76. How does LINQ work with non-traditional data sources like JSON or YAML?
var data = JsonSerializer.Deserialize<List<Product>>(jsonString);
var expensive = data.Where(p => p.Price > 100); // ordinary LINQ to Objects, post-deserializationThere's no "LINQ to JSON" provider translating queries into a JSON query language — the standard approach is deserializing JSON/YAML into plain C# objects (or a JsonDocument/JsonNode tree) first, then running normal LINQ to Objects over the resulting in-memory structure.
LINQ Expressions and Query Operators
Q77. What is an anonymous type in LINQ?
var result = products.Select(p => new { p.Name, p.Price });
// 'new { ... }' — a compiler-generated type with no name in your codeAn anonymous type is a compiler-synthesized read-only class inferred from the properties you list — extremely common in Select projections when you only need a subset of fields shaped for one specific query, without declaring a dedicated named class just for that.
Q78. List some LINQ query operators and explain their purpose.
| Operator | Purpose |
|---|---|
| Where | Filter elements by a predicate |
| Select / SelectMany | Project each element / flatten nested sequences |
| OrderBy / OrderByDescending | Sort ascending / descending |
| GroupBy | Partition into groups by a key |
| Join / GroupJoin | Combine two sequences by a matching key |
| Aggregate / Sum / Count / Average | Reduce a sequence to a single value |
Q79. How do you perform type checking within a LINQ query?
var shapes = items.Where(x => x is Circle);
var circles = items.OfType<Circle>(); // filters AND casts in one stepQ80. Explain the join operator in LINQ.
Join performs an inner join between two sequences based on matching keys, producing one output element per matching pair — against a database provider, it translates to a SQL INNER JOIN; for LINQ to Objects, it builds an internal lookup for efficiency rather than a naive nested loop.
Dynamic LINQ and Runtime Queries
Q81. What is Dynamic LINQ and why might you use it?
Dynamic LINQ (the System.Linq.Dynamic.Core package) lets you express a query's predicate/sort/select as a string parsed at runtime — for scenarios where the filter/sort criteria isn't known until runtime (a user-configurable report builder, a generic search endpoint), rather than every possible query being hand-written in code ahead of time.
Q82. How can you build LINQ queries dynamically at runtime?
// Using System.Linq.Dynamic.Core
var results = products
.Where("Price > @0", 100)
.OrderBy("Name")
.ToDynamicList();
// Or by manually building an Expression tree:
var param = Expression.Parameter(typeof(Product), "p");
var body = Expression.GreaterThan(Expression.Property(param, "Price"), Expression.Constant(100m));
var lambda = Expression.Lambda<Func<Product, bool>>(body, param);
var filtered = products.Where(lambda.Compile());Q83. Discuss the security implications of using Dynamic LINQ in an application.
If the query string comes from user input unsanitized, it's a real injection vector — a malicious "filter" string could reach into properties or invoke behavior the application never intended to expose. Restrict dynamic queries to a known allow-list of fields/operators, never pass raw user text straight into the parser.
Q84. Can LINQ expressions be serialized or sent over a network?
Expression trees aren't directly JSON-serializable out of the box (they contain compiled delegates/method references that don't round-trip cleanly), so sending a "query" over the network usually means serializing a simpler intermediate representation (a filter DSL, an OData query string) and reconstructing the actual expression tree/LINQ query on the receiving side, rather than serializing Expression<T> itself.
Cross-Cutting Concerns with LINQ
Q85. How do you address concerns such as logging and validation in LINQ?
These generally live outside the query itself — validate inputs before constructing the query (not inside a predicate, which a database provider might not even be able to translate), and log around the query (before/after materialization), since a lambda passed into a provider-translated query can't reliably run arbitrary side-effecting code like a logger call.
Q86. What is a predicate builder and how is it used in LINQ?
Expression<Func<Product, bool>> predicate = p => true;
if (minPrice.HasValue)
predicate = predicate.And(p => p.Price >= minPrice.Value);
if (category != null)
predicate = predicate.And(p => p.Category == category);
var results = products.Where(predicate);A predicate builder (commonly via the LinqKit library's .And()/.Or() extensions on Expression<Func<T,bool>>) composes filter conditions dynamically and safely, as real expression trees a provider can still translate — for building up a search filter from several optional criteria without resorting to string-based Dynamic LINQ.
Q87. Explain the concept of LINQ query continuations and how to use them.
var query = from p in products
group p by p.Category into g
select new { Category = g.Key, Count = g.Count() };
// 'into g' is the query continuation — g refers to the group going forwardA query continuation (the into keyword in query syntax) lets you name the result of a group/select clause and continue querying against it, effectively chaining a second query stage onto the first within one query-syntax expression.
Q88. How do you use attributes to control the behavior of LINQ to SQL?
[Table(Name = "Customers")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
}LINQ Testing and Mocking
Q89. How do you test LINQ queries or ensure that they produce the expected results?
[Fact]
public void FiltersOnlyActiveCustomers()
{
var customers = new List<Customer> {
new() { Name = "A", IsActive = true },
new() { Name = "B", IsActive = false },
};
var result = customers.Where(c => c.IsActive).ToList();
Assert.Single(result);
Assert.Equal("A", result[0].Name);
}LINQ to Objects queries are just plain C# — test them with a normal in-memory list of test data and assert on the result, no special tooling required.
Q90. What strategies can you use for mocking LINQ data contexts for unit testing?
var mockSet = new List<Product> { /* test data */ }
.AsQueryable()
.BuildMockDbSet(); // via a library like MockQueryable
var mockContext = new Mock<AppDbContext>();
mockContext.Setup(c => c.Products).Returns(mockSet.Object);Mocking IQueryable<T> convincingly is trickier than a plain list, because the mock needs to support the actual LINQ provider methods EF Core calls — libraries like MockQueryable exist specifically to wrap an in-memory list as a fully functional mock IQueryable<T>/DbSet<T>. Many teams prefer EF Core's own in-memory or SQLite provider for tests instead, since it exercises real query translation rather than a mocked substitute.
Q91. Describe an approach to mock LINQ to Entities when testing.
Use EF Core's InMemory provider (or a real SQLite in-memory database, which more faithfully catches provider-translation issues a fake in-memory provider might mask) configured in place of the real connection string for tests — the DbContext and LINQ queries run unmodified against a lightweight throwaway database instead of a real production one.
LINQ in .NET Core and .NET 5/6+
Q92. How has LINQ evolved with the introduction of .NET Core and later versions?
The core LINQ to Objects API itself has stayed largely stable — what's evolved is what surrounds it: EF Core replaced LINQ to SQL/EF6 as the primary ORM, async streaming (IAsyncEnumerable<T>) was added, and each .NET release has added a handful of new/optimized operators (MinBy/MaxBy, Chunk, DistinctBy, and others across .NET 6+).
Q93. What new features have been added to LINQ in .NET 5/6+?
| Method (added .NET 6) | Purpose |
|---|---|
| Chunk(size) | Splits a sequence into fixed-size batches |
| DistinctBy / UnionBy / IntersectBy / ExceptBy | Set operators keyed by a selector, not the whole element |
| MaxBy / MinBy | Returns the element with the max/min key, not just the key value |
| Zip (3-sequence overload) | Combines three sequences element-wise, not just two |
Q94. Are there any differences in how you write LINQ queries for .NET Framework vs. .NET Core?
The LINQ syntax itself is identical — the differences are around what's available in the surrounding ecosystem: .NET Core/.NET 5+ doesn't ship LINQ to SQL at all (EF Core is the path forward), and the newer convenience operators above simply don't exist on older .NET Framework target frameworks.
Contemporary Uses of LINQ
Q95. How is LINQ relevant in modern web development with .NET?
It's the default way ASP.NET Core applications query data — EF Core's LINQ provider for the database layer, plus LINQ to Objects everywhere else (shaping API response DTOs, filtering in-memory collections, aggregating request data) — genuinely hard to write idiomatic modern .NET without using LINQ constantly.
Q96. Can LINQ be used for data analysis or machine learning tasks?
For lightweight aggregation/transformation of in-memory datasets (grouping, summarizing, filtering) LINQ works fine and reads cleanly; for genuine large-scale data science, ML.NET or a proper data-processing framework is the better tool — LINQ isn't built for the vectorized numerical computation heavy ML work actually needs.
Q97. Discuss the usage of LINQ in functional programming practices.
LINQ is C#'s clearest expression of functional-programming ideas — pure, composable, higher-order functions (Where/Select taking a function as an argument), immutability (LINQ operators return new sequences rather than mutating the source), and declarative pipelines instead of imperative step-by-step mutation.
Q98. How does LINQ enable more declarative programming in .NET?
You describe the desired result ("the names of active customers, sorted") rather than the steps to produce it ("loop, check a condition, add to a list, then sort the list") — the same declarative-over-imperative shift that SQL itself represents, just embedded directly into C#.
LINQ in Concurrency and Parallelism
Q99. How do you work with LINQ in multi-threaded or parallel environments?
Plain LINQ to Objects queries are read-only and side-effect-free by convention, so querying the same immutable/unmodified source from multiple threads is safe — the risk is entirely in what you do with results afterward (mutating shared state in a Select's lambda, for instance), which needs its own synchronization exactly like any other multi-threaded code.
Q100. What is PLINQ and how does it differ from regular LINQ?
var results = numbers
.AsParallel()
.Where(n => IsExpensiveCheck(n))
.ToList();How PLINQ parallelizes a query
Source sequence
AsParallel() opts in
Partitioning
The sequence is split across available cores
Parallel processing
Each partition runs the query independently
Merge
Results are combined back into one sequence
PLINQ (Parallel LINQ) is LINQ to Objects with an added .AsParallel() that partitions the source data across multiple cores/threads and merges the results — a real speedup for CPU-bound work over a large enough dataset, but pure overhead (partitioning/coordination cost with no benefit) for small collections or I/O-bound work, which is exactly why it's opt-in rather than the default.
Test yourself
A quick mock test covering the ground above — the rapid-fire round that often opens a LINQ interview before the deeper follow-ups.
Question 1 of 10
Score: 0 / 0
1. What's the core difference between IEnumerable<T> and IQueryable<T>?