LINQ Operators and Lambda Expression

LINQ Operators and Lambda Expression - Syntax & Examples
LINQ is a cool feature in C# 3.0. Most of the developers are struggling for the syntax and examples. Here I have collected various examples for each operator in LINQ and the equivalent Lambda Expressions. 

Where

IEnumerable<Product> x = products.Where(p => p.UnitPrice >= 10);
IEnumerable<Product> x =
from p in products
where p.UnitPrice >= 10
select p;

Select

IEnumerable<string> productNames = products.Select(p => p.Name);
IEnumerable<string> productNames =from p in products select p.Name;
var namesAndPrices =
products.
Where(p => p.UnitPrice >= 10).
Select(p =>
new { p.Name, p.UnitPrice }).
ToList();

IEnumerable<int> indices =
products.
Select((product, index) =>
new { product, index }).
Where(x => x.product.UnitPrice >= 10).
Select(x => x.index);

SelectMany

IEnumerable<Order> orders = customers.
Where(c => c.Country == "Denmark").
SelectMany(c => c.Orders);

var namesAndOrderIDs = customers.
Where(c => c.Country == "Denmark").
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).
Select(o =>
new { o.Customer.Name, o.OrderID });

var namesAndOrderIDs = customers.Where(c => c.Country == "Denmark").
SelectMany(c => c.Orders, (c,o) => new { c, o }).
Where(co => co.o.OrderDate.Year == 2005).
Select(co =>
new { co.c.Name, co.o.OrderID });

var namesAndOrderIDs = from c in customers where c.Country == "Denmark"
from o in c.Orders where o.OrderDate.Year == 2005
select new { c.Name, o.OrderID };

Take

IEnumerable<Product> MostExpensive10 =
products.OrderByDescending(p => p.UnitPrice).Take(10);

Skip

IEnumerable<Product> AllButMostExpensive10 =
products.OrderByDescending(p => p.UnitPrice).Skip(10);

TakeWhile SkipWhile

s.TakeWhile(p) s.SkipWhile(p)

Join
var custOrders =
customers.Join(ordersc => c.CustomerIDo => o.CustomerID,
(co=> new { c.Nameo.OrderDateo.Total });

var custOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID
select new { c.Nameo.OrderDateo.Total };

GroupJoin

var custTotalOrders =
customers.
GroupJoin(orders, c => c.CustomerID, o => o.CustomerID,
(c, co) =>
new { c.Name, TotalOrders = co.Sum(o => o.Total) }
);

var custTotalOrders =
from c in customers
join o in orderson c.CustomerID equals o.CustomerID into co
select new { c.Name, TotalOrders = co.Sum(o => o.Total) };

var custTotalOrders = from c in customers
join o in orderson c.CustomerID equals o.CustomerID
select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =from c in customers
join o in orderson c.CustomerID equals o.CustomerID into co
from o in co
select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =from c in customers
join o in orderson c.CustomerID equals o.CustomerID into co
from o in co.DefaultIfEmpty(emptyOrder)
select new { c.Name, o.OrderDate, o.Total };

Concat

IEnumerable<string> locations =customers.Select(c => c.City).
Concat(customers.Select(c => c.Region)).
Concat(customers.Select(c => c.Country)).
Distinct();

IEnumerable<string> locations =new[] {
customers.Select(c => c.City),
customers.Select(c => c.Region),
customers.Select(c => c.Country),
}.SelectMany(s => s).
Distinct();

OrderBy / ThenBy

IEnumerable<Product> orderedProducts1 =products.
OrderBy(p => p.Category).
ThenByDescending(p => p.UnitPrice).
ThenBy(p => p.Name);

IEnumerable<Product> orderedProducts1 =from p in products
orderby p.Category, p.UnitPrice descending, p.Name
select p;

IEnumerable<Product> orderedProducts2 =products.
Where(p => p.Category == "Beverages").
OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase);

IEnumerable<string> orderedProductNames =products.
Where(p => p.Category == "Beverages").
Select(p => p.Name).OrderBy(x => x);

GroupBy

IEnumerable<IGrouping<string,Product>> productsByCategory =products.GroupBy(p => p.Category);
IEnumerable<IGrouping<string,string>> productNamesByCategory =products.GroupBy(p => p.Category, p => p.Name);

Distinct

IEnumerable<string> productCategories =products.Select(p => p.Category).Distinct();

AsEnumerable

Table<Customer> custTable = GetCustomersTable();
var query = custTable.AsEnumerable().Where(c => IsGoodCustomer(c));

ToArray

string[] customerCountries =customers.Select(c => c.Country).Distinct().ToArray();

ToList

List<Customer> customersWithOrdersIn2005 =
customers.
Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
ToList();

ToDictionary

Dictionary<int,Order> orders =customers.
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).ToDictionary(o => o.OrderID);

Dictionary<string,decimal> categoryMaxPrice =products.
GroupBy(p => p.Category).
ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));

ToLookup

Lookup<string,Product> productsByCategory =products.ToLookup(p => p.Category);
IEnumerable<Product> beverages = productsByCategory["Beverage"];

OfType

List<Person> persons = GetListOfPersons();
IEnumerable<Employee> employees = persons.OfType<Employee>();

Cast

ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 = objects.Cast<Order>().
Where(o => o.OrderDate.Year == 2005);

ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 =from Order o in objects
where o.OrderDate.Year == 2005
select o;

First

string phone = "206-555-1212";
Customer c = customers.First(c => c.Phone == phone);

Single

int id = 12345;
Customer c = customers.Single(c => c.CustomerID == id);

ElementAt

Product thirdMostExpensive =
products.OrderByDescending(p => p.UnitPrice).ElementAt(2);

Range

int[] squares = Enumerable.Range(0, 100).Select(x => x * x).ToArray();
Repeat

long[] x = Enumerable.Repeat(-1L, 256).ToArray();

Empty

IEnumerable<Customer> noCustomers = Enumerable.Empty<Customer>();

Any

bool b = products.Any(p => p.UnitPrice >= 100 && p.UnitsInStock == 0);

All

IEnumerable<string> fullyStockedCategories =products.
GroupBy(p => p.Category).
Where(g => g.Group.All(p => p.UnitsInStock > 0)).
Select(g => g.Key);

Count

int count = customers.Count(c => c.City == "London");

Sum

int year = 2005;
var namesAndTotals =customers.
Select(c =>
new {c.Name,
TotalOrders =c.Orders.Where(o => o.OrderDate.Year == year).
Sum(o => o.Total)});

Min

var minPriceByCategory =products.
GroupBy(p => p.Category).Select(g =>
new {
Category = g.Key,MinPrice = g.Group.Min(p => p.UnitPrice)
});

Max

decimal largestOrder =customers.
SelectMany(c => c.Orders).Where(o => o.OrderDate.Year == 2005).
Max(o => o.Total);

Average

var averageOrderTotals =customers.
Select(c =>
new {c.Name,AverageOrderTotal = c.Orders.Average(o => o.Total)});

Aggregate

var longestNamesByCategory =products.
GroupBy(p => p.Category).Select(g =>
new {
Category = g.Key,LongestName =
g.Group.Select(p => p.Name).
Aggregate((s, t) => t.Length > s.Length ? t : s)
});


You can also query the array variables using LINQ.

Here are sample example for this.
In this example there is an array of integer values which contains various number, Now we want to get numbers in array which is greater then 5.
We can do this without FOR loop.

There are two possible way to do this. One is using LINQ Query and Second is Using LAMBDA Expression

C# Example using LINQ Query :
int[] arrayNumbers = new[] { 1,2,5,9,10,1,0,9,5,6,4,3,2};
int[] selectedNumber = (from an in arrayNumbers where an > 5 select an).ToArray();

C# Example using LAMBDA Expression:
int[] arrayNumbers = new[] { 1,2,5,9,10,1,0,9,5,6,4,3,2};
int[] selectedNumberLambda = arrayNumbers.Where(an => an > 5).ToArray();


:)

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives