.NET ProgrammingUnit 76 min read
LINQ in C: Queries, Lambda, and Data Processing
Unit 7 of .NET Programming covers Language Integrated Query (LINQ), its syntax, methods, and real-world applications in C. Learn how LINQ simplifies data querying across collections, databases, and XML, with step-by-step examples, comparisons, and exam-focused insights.
TAKEAWAYS:
- LINQ unifies querying syntax for collections, databases, and XML using C# syntax, reducing boilerplate code.
- Key components: query syntax (SQL-like) and method syntax (lambda expressions) for flexibility.
- LINQ methods like
Where,Select,OrderBy, andGroupBytransform data efficiently. - LINQ to SQL bridges C# with SQL Server, enabling seamless database operations.
- Real-world use: eSewa (filtering transactions), Daraz (searching products), and Ncell (analyzing call logs).
- Exam focus: tracing LINQ queries, comparing syntax types, and debugging common errors.
1. Introduction to LINQ
LINQ (Language Integrated Query) is a C# feature that allows querying data from collections, databases, XML, and more using declarative syntax. Introduced in .NET 3.5, LINQ integrates querying directly into C# code, reducing the need for separate query languages (e.g., SQL).
Why Use LINQ?
- Unified syntax: Works across different data sources (arrays, lists, databases).
- Readability: Resembles SQL but uses C# syntax.
- Type safety: Compile-time checks reduce runtime errors.
- Performance: Optimized queries via deferred execution (lazy evaluation).
LINQ Flavors
LINQ is categorized based on the data source:
mindmap
root((LINQ))
LINQ to Objects
LINQ to SQL
LINQ to XML
LINQ to Entities
LINQ to JSON2. LINQ Query Syntax vs. Method Syntax
LINQ supports two syntaxes:
- Query Syntax (SQL-like):
var result = from item in collection where item.Property > 10 select item; - Method Syntax (Lambda-based):
var result = collection.Where(item => item.Property > 10);
Comparison Table
| Feature | Query Syntax | Method Syntax |
|---|---|---|
| Readability | SQL-like, intuitive | Concise, functional |
| Flexibility | Less flexible | More flexible (e.g., chaining) |
| Debugging | Easier to trace | Requires lambda understanding |
| Use Case | Simple queries | Complex transformations |
3. Common LINQ Operators
LINQ operators are categorized into:
- Query Operators (filtering, projecting):
Where: Filters data.Select: Projects data.OrderBy: Sorts data.
- Aggregation Operators:
Sum,Average,Count.
- Grouping Operators:
GroupBy: Groups data by a key.
- Set Operators:
Distinct,Union,Intersect.
Example: Filtering and Sorting
Scenario: Filter employees earning > 50,000 and sort by name.
List<Employee> employees = GetEmployees();
var result = employees
.Where(e => e.Salary > 50000)
.OrderBy(e => e.Name)
.ToList();
Trace Table:
| Step | Operation | Output (First 2 Rows) |
|---|---|---|
| Initial List | All employees | [Alice, Bob, Carol, Dave] |
After Where |
Salary > 50,000 | [Alice, Dave] |
After OrderBy |
Sorted by Name | [Alice, Dave] |
4. LINQ to SQL: Database Queries
LINQ to SQL maps C# classes to SQL Server tables, enabling strongly typed database access.
Example: Querying a Database
using (var context = new DataContext("ConnectionString"))
{
var customers = from c in context.Customers
where c.City == "Kathmandu"
select c;
foreach (var customer in customers)
{
Console.WriteLine(customer.Name);
}
}
Generated SQL:
SELECT [t0].[Id], [t0].[Name], [t0].[City]
FROM [Customers] AS [t0]
WHERE [t0].[City] = @p0
5. LINQ to XML
LINQ to XML allows querying and manipulating XML documents in C#.
Example: Parsing XML
XDocument doc = XDocument.Load("data.xml");
var books = from book in doc.Descendants("Book")
where (string)book.Element("Price") > "50"
select book.Element("Title").Value;
foreach (var title in books)
{
Console.WriteLine(title);
}
XML Input:
<Books>
<Book>
<Title>C# Guide</Title>
<Price>60</Price>
</Book>
<Book>
<Title>ASP.NET Core</Title>
<Price>45</Price>
</Book>
</Books>
In the Real World
eSewa (Transaction Filtering)
- Uses LINQ to filter transactions by date, amount, or user.
- Example:
transactions.Where(t => t.Date > DateTime.Now.AddDays(-30)).
Daraz (Product Search)
- LINQ queries products by category, price, or rating.
- Example:
products.Where(p => p.Price < 1000 && p.Rating > 4).
Ncell (Call Log Analysis)
- LINQ aggregates call duration or counts calls per user.
- Example:
callLogs.GroupBy(c => c.UserId).Select(g => new { User = g.Key, TotalCalls = g.Count() }).
6. LINQ Performance Considerations
- Deferred Execution: Queries execute only when iterated (e.g.,
ToList()forces evaluation). - Inefficient Queries: Avoid
ToList()prematurely; useyieldfor large datasets. - Database Queries: LINQ to SQL translates to SQL, but complex operations may generate inefficient queries.
Example: Deferred Execution
var query = employees.Where(e => e.IsActive); // Not executed yet
foreach (var emp in query) // Executes here
{
Console.WriteLine(emp.Name);
}
7. Common LINQ Pitfalls
- Null Reference Exceptions:
- Always check for
nullin collections.
var safeQuery = employees?.Where(e => e != null); - Always check for
- Overusing
ToList():- Can load entire datasets into memory.
- Incorrect Grouping:
- Ensure keys are hashable (e.g., avoid complex objects as keys).
Exam Tip
- Focus on:
- Tracing LINQ queries step-by-step (e.g.,
Where→Select→OrderBy). - Comparing query vs. method syntax.
- Writing LINQ to SQL queries and predicting SQL output.
- Tracing LINQ queries step-by-step (e.g.,
- Avoid:
- Memorizing syntax; prioritize understanding logic.
- Overcomplicating queries in exams (stick to basics like
Where,Select).
- Practice:
- Given a dataset, write LINQ to filter/sort/group.
- Debug LINQ errors (e.g., null checks, incorrect lambdas).
Visual Summary:
flowchart TD
A["LINQ"] --> B["Query Syntax"]
A --> C["Method Syntax"]
B --> D["SQL-like"]
C --> E["Lambda-based"]
D --> F["Readable"]
E --> G["Flexible"]
A --> H["LINQ to SQL"]
A --> I["LINQ to XML"]
H --> J["Database Queries"]
I --> K["XML Parsing"]Based on the TU BITM syllabus for .NET Programming (IT275), unit 7.
Discussion
Loading…