In C#, LINQ (Language Integrated Query) has several types or providers, each designed to work with different types of data sources. Here are the main types/providers of LINQ.
There are several types of LINQ:
Here are the main types of LINQ in C# explained:
LINQ to Objects
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4
}
LINQ to SQL
using (DataContext context = new DataContext(connectionString))
{
var employees = from e in context.GetTable<Employee>()
where e.Department == "Sales"
select e;
foreach (var employee in employees)
{
Console.WriteLine(employee.Name);
}
}
LINQ to XML
XElement xml = XElement.Load("employees.xml");
var employees = from e in xml.Elements("employee")
where (string)e.Element("department") == "Sales"
select e;
foreach (var employee in employees)
{
Console.WriteLine(employee.Element("name").Value);
}
LINQ to DataSet
DataSet ds = GetDataSet(); // Assume this method returns a populated DataSet
var employees = from e in ds.Tables["Employees"].AsEnumerable()
where e.Field("Department") == "Sales"
select e;
foreach (var employee in employees)
{
Console.WriteLine(employee.Field("Name"));
}
LINQ to Entities (Entity Framework)
using (var context = new MyDbContext())
{
var employees = from e in context.Employees
where e.Department == "Sales"
select e;
foreach (var employee in employees)
{
Console.WriteLine(employee.Name);
}
}