Filtering Data in C# using LINQ: Extracting Specific Properties
Learn efficient techniques for filtering data and extracting specific properties from collections of objects in C#. This tutorial demonstrates using LINQ (Language Integrated Query) to filter data based on conditions and select desired properties, providing concise and readable code for data manipulation.
Filtering Data in C# to Extract Single Properties
Introduction
This article demonstrates how to filter collections of data objects in C# to extract a specific property based on certain conditions. We'll use LINQ (Language Integrated Query) to achieve this efficiently.
Scenario: Filtering Student Data
Imagine a list of students, each with properties like Name
, Age
, RollNumber
, etc. A teacher wants to get a list of only the names of students who are eligible to vote (age >= 18).
Using LINQ for Filtering
LINQ provides methods like Where
(to filter) and Select
(to extract specific properties) to make this process easy.
Example 1: Filtering Employee Salaries
This example filters a list of Employee
objects to get the names of employees with salaries above $55,000.
Example 1: Employee Salaries
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public class Employee {
public string Name { get; set; }
public int EmployeeID { get; set; }
public double Salary { get; set; }
}
static void Main(string[] args) {
List<Employee> employees = new List<Employee> {
new Employee { Name = "Laxman", EmployeeID = 101, Salary = 50000 },
new Employee { Name = "Sita", EmployeeID = 102, Salary = 60000 },
new Employee { Name = "Ramu", EmployeeID = 103, Salary = 70000 },
new Employee { Name = "Anji", EmployeeID = 104, Salary = 45000 }
};
IEnumerable<string> highSalaryEmployees = employees
.Where(employee => employee.Salary > 55000)
.Select(employee => employee.Name);
Console.WriteLine("Employees with salaries above $55,000:");
foreach (string employeeName in highSalaryEmployees) {
Console.WriteLine(employeeName);
}
}
}
Output Example 1
Employees with salaries above $55,000:
Sita
Ramu
Explanation Example 1
The code defines an Employee
class, creates a list of employees, and then uses LINQ's Where
to filter employees based on salary and Select
to extract their names.
Example 2: Aggregating Transaction Amounts
This example uses the Aggregate
method to calculate the total sales amount from a list of Transaction
objects.
Example 2: Total Sales
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public class Transaction {
public string Salesperson { get; set; }
public double Amount { get; set; }
}
static void Main(string[] args) {
List<Transaction> transactions = new List<Transaction> {
new Transaction { Salesperson = "Ajay", Amount = 500 },
new Transaction { Salesperson = "Vijay", Amount = 700 },
new Transaction { Salesperson = "Sanjay", Amount = 900 }
};
double totalSales = transactions
.Aggregate(0.0, (total, transaction) => total + transaction.Amount);
Console.WriteLine("Total sales amount: $" + totalSales);
}
}
Output Example 2
Total sales amount: $2100
Explanation Example 2
This uses Aggregate
to accumulate the Amount
property from each transaction.
Example 3: Complex Filtering with Joins
This example demonstrates a more complex scenario involving two lists: Product
and InventoryStatus
. It finds the names of affordable products that are currently in stock.
Example 3: Products in Stock
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public class Product {
public string Name { get; set; }
public int ProductID { get; set; }
public double Price { get; set; }
}
public class InventoryStatus {
public int ProductID { get; set; }
public bool InStock { get; set; }
}
static void Main(string[] args) {
// ... (Product and InventoryStatus lists defined here as in the original example) ...
IEnumerable<string> affordableProducts = products
.Join(inventoryStatusList,
product => product.ProductID,
inventory => inventory.ProductID,
(product, inventory) => new { product, inventory })
.Where(pair => pair.product.Price < 500 && pair.inventory.InStock)
.Select(pair => pair.product.Name);
Console.WriteLine("Affordable products currently in stock:");
foreach (string productName in affordableProducts) {
Console.WriteLine(productName);
}
}
}
Output Example 3
Affordable products currently in stock:
Headphones
Explanation Example 3
This uses a Join
to combine the two lists based on ProductID
, then filters and selects the names of matching products.
Conclusion
LINQ offers powerful and flexible ways to filter and extract data in C#. The choice of methods (Where
, Select
, Aggregate
, Join
, etc.) depends on the complexity of the filtering requirements.