LINQ to Objects in C# Programming
LINQ to Objects is a powerful feature in C# that allows you to query and manipulate data stored in objects such as arrays, lists, and other collections. LINQ (Language Integrated Query) provides both query syntax and method syntax to perform common operations such as filtering, ordering, grouping, and aggregating data. In this tutorial, we'll cover these operations with step-by-step examples.
Step 1: Setting Up LINQ to Objects
Before using LINQ to Objects, make sure to include the System.Linq
namespace in your program:
using System.Linq;
LINQ methods are part of this namespace, so it is necessary to import it to access LINQ functionality.
Step 2: Query Syntax vs Method Syntax
LINQ to Objects supports two types of syntax:
- Query Syntax: Similar to SQL queries, it is declarative and easy to understand.
- Method Syntax: Uses LINQ extension methods like
Where
,Select
,OrderBy
, etc., and is more functional in style.
Example: Query Syntax
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax: Find even numbers
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
Console.WriteLine("Even numbers (Query Syntax):");
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
The query syntax uses the from
keyword to define the data source, the where
clause to filter data, and the select
keyword to specify what to return.
Example: Method Syntax
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method syntax: Find even numbers
var evenNumbers = numbers.Where(num => num % 2 == 0);
Console.WriteLine("Even numbers (Method Syntax):");
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
The method syntax uses the Where
method to filter the numbers based on a lambda expression.
Step 3: Filtering Data
Filtering data allows you to select only the elements that satisfy a given condition. Below is an example where we filter a list of integers to get numbers greater than 5.
Query Syntax Example: Filtering
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax: Find numbers greater than 5
var greaterThanFive = from num in numbers
where num > 5
select num;
Console.WriteLine("Numbers greater than 5 (Query Syntax):");
foreach (var num in greaterThanFive)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
Method Syntax Example: Filtering
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method syntax: Find numbers greater than 5
var greaterThanFive = numbers.Where(num => num > 5);
Console.WriteLine("Numbers greater than 5 (Method Syntax):");
foreach (var num in greaterThanFive)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
Step 4: Ordering Data
LINQ also allows you to order your data. Below is an example where we sort numbers in ascending order using both query syntax and method syntax.
Query Syntax Example: Ordering
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 9, 2, 5, 7, 1, 8, 4, 6, 3, 10 };
// Query syntax: Sort numbers in ascending order
var sortedNumbers = from num in numbers
orderby num
select num;
Console.WriteLine("Numbers in ascending order (Query Syntax):");
foreach (var num in sortedNumbers)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
Method Syntax Example: Ordering
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 9, 2, 5, 7, 1, 8, 4, 6, 3, 10 };
// Method syntax: Sort numbers in ascending order
var sortedNumbers = numbers.OrderBy(num => num);
Console.WriteLine("Numbers in ascending order (Method Syntax):");
foreach (var num in sortedNumbers)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
Step 5: Grouping Data
Grouping data allows you to organize the elements of a collection into groups based on a specified key. Below is an example of grouping people by their age using LINQ.
Query Syntax Example: Grouping
using System;
using System.Linq;
using System.Collections.Generic;
namespace LINQToObjectsExample
{
class Program
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main()
{
List people = new List
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "Jake", Age = 25 },
new Person { Name = "Jill", Age = 30 }
};
// Query syntax: Group people by age
var groupedByAge = from person in people
group person by person.Age into ageGroup
select ageGroup;
Console.WriteLine("People grouped by age (Query Syntax):");
foreach (var group in groupedByAge)
{
Console.WriteLine("Age: " + group.Key);
foreach (var person in group)
{
Console.WriteLine(person.Name);
}
}
Console.ReadLine();
}
}
}
Method Syntax Example: Grouping
using System;
using System.Linq;
using System.Collections.Generic;
namespace LINQToObjectsExample
{
class Program
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main()
{
List people = new List
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "Jake", Age = 25 },
new Person { Name = "Jill", Age = 30 }
};
// Method syntax: Group people by age
var groupedByAge = people.GroupBy(person => person.Age);
Console.WriteLine("People grouped by age (Method Syntax):");
foreach (var group in groupedByAge)
{
Console.WriteLine("Age: " + group.Key);
foreach (var person in group)
{
Console.WriteLine(person.Name);
}
}
Console.ReadLine();
}
}
}
Step 6: Aggregating Data
LINQ also allows you to aggregate data, such as finding the sum, average, minimum, and maximum values. Below is an example where we calculate the total sum of the numbers in an array.
Query Syntax Example: Aggregating
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax: Calculate the sum of numbers
var sum = (from num in numbers
select num).Sum();
Console.WriteLine("Sum of numbers (Query Syntax): " + sum);
Console.ReadLine();
}
}
}
Method Syntax Example: Aggregating
using System;
using System.Linq;
namespace LINQToObjectsExample
{
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method syntax: Calculate the sum of numbers
var sum = numbers.Sum();
Console.WriteLine("Sum of numbers (Method Syntax): " + sum);
Console.ReadLine();
}
}
}
Step 7: Conclusion
LINQ to Objects is a powerful feature that allows you to query, filter, order, group, and aggregate data in a concise and readable way. By using LINQ, you can simplify many common data operations and make your code more declarative and expressive. In this tutorial, we have covered:
- Query Syntax vs Method Syntax
- Filtering, Ordering, Grouping, and Aggregating Data
Now you can apply these LINQ techniques to work with collections such as arrays, lists, and other objects in C#.