Friday 13 January 2012

LINQ Operators and Lambda Expression - Syntax & - Examples


The article contains only syntax and example of Linq and Lamda expression, hope this will quit informative for you and thanks to you to give your valuable time in advance.

public class Customers
{
    public string CustomerID;
    public string ContactName;
    public string Phone;
    public string City;
    public string Country;
}
public class Orders
{
    public int OrderID;
    public string CustomerID;
    public DateTime OrderDate;
}

Where

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) to filter.
predicate
Type: System.Func(Of TSource, Boolean)
A function to test each element for a condition.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) that contains elements from the input sequence that satisfy the condition.
#region Where
List<Customers> Customers = new List<Customers>();
IEnumerable<Customers> x = Customers.Where(p => p.ContactName == "MR. ABCD");

IEnumerable<Customers> x = from p in Customers
                           where p.ContactName == "MR. ABCD"
                           select p;
#endregion

Select

Type Parameters

TSource
The type of the elements of source.
TResult
The type of the value returned by selector.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
A sequence of values to invoke a transform function on.
selector
Type: System.Func(Of TSource, TResult)
A transform function to apply to each element.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TResult)
An IEnumerable(Of T) whose elements are the result of invoking the transform function on each element of source.
#region Select
 List<Customers> Customers = new List<Customers>();
 IEnumerable<string> CustomerNames = Customers.Select(p => p.ContactName);

 IEnumerable<string> CustomerNames = from p in Customers select p.ContactName;

 var namesAndCity =
     Customers.
     Where(p => p.City == "Kolkata").
     Select(p => new { p.ContactName, p.City }).
     ToList();

 IEnumerable<int> indices = Customers.
                            Select((Customer, index) => new { Customer, index }).
                            Where(x => x.Customer.ContactName == "Kolkata").
                            Select(x => x.index);

#endregion

SelectMany

Type Parameters

TSource
The type of the elements of source.
TResult
The type of the elements of the sequence returned by selector.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
A sequence of values to project.
selector
Type: System.Func(Of TSource, IEnumerable(Of TResult))
A transform function to apply to each element.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TResult)
An IEnumerable(Of T) whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
#region SelectMany
List<Customers> Customers = new List<Customers>();
IEnumerable<Orders> 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.CustomerID, 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.ContactName, 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.ContactName, o.OrderID };
#endregion

Take

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
The sequence to return elements from.
count
Type: System.Int32
The number of elements to return.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) that contains the specified number of elements from the start of the input sequence.
#region Take
List<Customers> Customers = new List<Customers>();
IEnumerable<Customers> MostExpensive10 = Customers.OrderByDescending(p => p.ContactName).Take(10);
#endregion

Skip

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Linq.IQueryable(Of TSource)
An IQueryable(Of T) to return elements from.
count
Type: System.Int32
The number of elements to skip before returning the remaining elements.

Return Value

Type: System.Linq.IQueryable(Of TSource)
An IQueryable(Of T) that contains elements that occur after the specified index in the input sequence.
#region Skip
List<Customers> Customers = new List<Customers>();
IEnumerable<Customers> AllButMostExpensive10 = Customers.OrderByDescending(p => p.ContactName).Skip(10);
#endregion

SkipWhile TakeWhile

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) to return elements from.
predicate
Type: System.Func(Of TSource, Boolean)
A function to test each element for a condition.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
#region SkipWhile TakeWhile
List<Customers> Customers = new List<Customers>();
var query9 = Customers.Select((cust, index) => new { cust, index })
             .OrderBy(c => c.cust.Country)
             .SkipWhile(c => c.cust.Country != "USA")
             .TakeWhile(c => c.cust.Country == "USA")
             .Select(c => new { c.cust.CustomerID, c.cust.ContactName, c.index });

#endregion

Join
#region Join
List<Customers> Customers = new List<Customers>();
List<Orders> Orders = new List<Orders>();
var custOrders = Customers.
                 Join(Orders, c => c.CustomerID, o => o.CustomerID,
                    (c, o) => new { c.CustomerID, o.OrderDate, o.OrderID });
var custOrders = from c in Customers
                 join o in Orders on c.CustomerID equals o.CustomerID
                 select new { c.ContactName, o.OrderDate, o.OrderID };


#endregion

GroupJoin

Type Parameters

TOuter
The type of the elements of the first sequence.
TInner
The type of the elements of the second sequence.
TKey
The type of the keys returned by the key selector functions.
TResult
The type of the result elements.

Parameters

outer
Type: System.Collections.Generic.IEnumerable(Of TOuter)
The first sequence to join.
inner
Type: System.Collections.Generic.IEnumerable(Of TInner)
The sequence to join to the first sequence.
outerKeySelector
Type: System.Func(Of TOuter, TKey)
A function to extract the join key from each element of the first sequence.
innerKeySelector
Type: System.Func(Of TInner, TKey)
A function to extract the join key from each element of the second sequence.
resultSelector
Type: System.Func(Of TOuter, IEnumerable(Of TInner), TResult)
A function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TResult)
An IEnumerable(Of T) that contains elements of type TResult that are obtained by performing a grouped join on two sequences.
#region GroupJoin
List<Customers> Customers = new List<Customers>();
List<Orders> Orders = new List<Orders>();
Orders emptyOrder = new Orders();

var custTotalOrders = Customers.
                      GroupJoin(Orders, c => c.CustomerID, o => o.CustomerID,
                      (c, co) => new { c.ContactName, TotalOrders = co.Sum(o => o.OrderID) });

var custTotalOrders = from c in Customers
                      join o in Orders on c.CustomerID equals o.CustomerID into co
                      select new { c.ContactName, TotalOrders = co.Sum(o => o.OrderID) };

var custTotalOrders = from c in Customers
                      join o in Orders on c.CustomerID equals o.CustomerID
                      select new { c.ContactName, o.OrderDate, o.OrderID };

var custTotalOrders = from c in Customers
                      join o in Orders on c.CustomerID equals o.CustomerID into co
                      from o in co
                      select new { c.ContactName, o.OrderDate, o.OrderID };

var custTotalOrders = from c in Customers
                      join o in Orders on c.CustomerID equals o.CustomerID into co
                      from o in co.DefaultIfEmpty(emptyOrder)
                      select new { c.ContactName, o.OrderDate, o.OrderDate };

#endregion

Concat

Type Parameters

TSource
The type of the elements of the input sequences.

Parameters

first
Type: System.Collections.Generic.IEnumerable(Of TSource)
The first sequence to concatenate.
second
Type: System.Collections.Generic.IEnumerable(Of TSource)
The sequence to concatenate to the first sequence.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) that contains the concatenated elements of the two input sequences.
#region Concat
List<Customers> Customers = new List<Customers>();

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

 IEnumerable<string> locations =  new[] {
            Customers.Select(c => c.ContactName),
            Customers.Select(c => c.City),
            Customers.Select(c => c.Country),
        }.SelectMany(s => s)
        .Distinct();
#endregion

OrderBy / ThenBy

Type Parameters

TSource
The type of the elements of source.
TKey
The type of the key returned by keySelector.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
A sequence of values to order.
keySelector
Type: System.Func(Of TSource, TKey)
A function to extract a key from an element.

Return Value

Type: System.Linq.IOrderedEnumerable(Of TSource)
An IOrderedEnumerable(Of TElement) whose elements are sorted according to a key.

#region OrderBy / ThenBy
List<Customers> Customers = new List<Customers>();
List<Orders> Orders = new List<Orders>();
Orders emptyOrder = new Orders();
IEnumerable<Customers> orderedCustomers1 =
            Customers.
            OrderBy(p => p.Country).
            ThenByDescending(p => p.ContactName).
            ThenBy(p => p.Phone);

IEnumerable<Customers> orderedCustomers2 =
                        from p in Customers
                        orderby p.Country, p.ContactName descending, p.Phone
                        select p;

IEnumerable<Customers> orderedCustomers3 =
                        Customers.
                        Where(p => p.Country == "India").
                        OrderBy(p => p.ContactName, StringComparer.CurrentCultureIgnoreCase);

IEnumerable<string> orderedProductNames =
                        Customers.
                        Where(p => p.Country == "India").
                        Select(p => p.ContactName).
                        OrderBy(x => x);
#endregion

GroupBy

Type Parameters

TSource
The type of the elements of source.
TKey
The type of the key returned by keySelector.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) whose elements to group.
keySelector
Type: System.Func(Of TSource, TKey)
A function to extract the key for each element.

Return Value

Type: System.Collections.Generic.IEnumerable(Of IGrouping(Of TKey, TSource))
An IEnumerable<IGrouping<TKey, TSource>> in C# or IEnumerable(Of IGrouping(Of TKey, TSource)) in Visual Basic where each IGrouping(Of TKey, TElement) object contains a sequence of objects and a key.

#region GroupBy
List<Customers> Customers = new List<Customers>();
List<Orders> Orders = new List<Orders>();
Orders emptyOrder = new Orders();

IEnumerable<IGrouping<string, Customers>> CustomersBy = Customers.GroupBy(p => p.Country);

IEnumerable<IGrouping<string, string>> CustomersNamesBy = Customers.GroupBy(p => p.ContactName, p => p.ContactName);
#endregion
#region Distinct
List<Customers> Customers = new List<Customers>();
List<Orders> Orders = new List<Orders>();
Orders emptyOrder = new Orders();

IEnumerable<string> cust = Customers.Select(p => p.ContactName).Distinct();

#endregion

AsEnumerable
#region AsEnumerable

Table<Customers> custTable = GetCustomersTable();
var query = custTable.AsEnumerable().Where(c => IsGoodCustomer(c));
DataTable dt = new DataTable();
var query = dt.AsEnumerable().Where(c => c.Field<String>("Name")=="Your Name");

#endregion

ToArray

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) to create an array from.

Return Value

Type: TSource()
An array that contains the elements from the input sequence.
#region ToArray
List<Customers> Customers = new List<Customers>();
string[] customer = Customers.Select(c => c.Country).Distinct().ToArray();
#endregion

ToList

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
The IEnumerable(Of T) to create a List(Of T) from.

Return Value

Type: System.Collections.Generic.List(Of TSource)
A List(Of T) that contains elements from the input sequence.
#region ToList
List<Customers> Customers = new List<Customers>();

List<Customers> customers = Customers.
                            Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
                            ToList();
           
#endregion

ToDictionary

Type Parameters

TSource
The type of the elements of source.
TKey
The type of the key returned by keySelector.

Parameters

source
keySelector
Type: System.Func(Of TSource, TKey)
A function to extract a key from each element.

Return Value

Type: System.Collections.Generic.Dictionary(Of TKey, TSource)
A Dictionary(Of TKey, TValue) that contains keys and values.

#region ToDictionary
List<Customers> Customers = new List<Customers>();

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

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

Lookup

Type Parameters

TKey
The type of the keys in the Lookup(Of TKey, TElement).
TElement
The type of the elements of each IEnumerable(Of T) value in the Lookup(Of TKey, TElement).
#region Lookup
List<Customers> Customers = new List<Customers>();

Lookup<string, Customers> Country = Customers.ToLookup(p => p.Country);
IEnumerable<Customers> ind = productsByCategory["india"];
#endregion

OfType

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

Cast

Type Parameters

TResult
The type to cast the elements of source to.

Parameters

source
Type: System.Collections.IEnumerable
The IEnumerable that contains the elements to be cast to type TResult.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TResult)
An IEnumerable(Of T) that contains each element of the source sequence cast to the specified type.
#region 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;
#endregion

First

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Linq.IQueryable(Of TSource)
The IQueryable(Of T) to return the first element of.

Return Value

Type: TSource
The first element in source.

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

Single

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) to return the single element of.

Return Value

Type: TSource
The single element of the input sequence.
#region Single
int id = 12345;
Customer c = customers.Single(c => c.CustomerID == id);
#endregion

ElementAt

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) to return an element from.
index
Type: System.Int32
The zero-based index of the element to retrieve.

Return Value

Type: TSource
The element at the specified position in the source sequence.

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

Range

Parameters

start
Type: System.Int32
The value of the first integer in the sequence.
count
Type: System.Int32
The number of sequential integers to generate.

Return Value

Type: System.Collections.Generic.IEnumerable(Of Int32)
An IEnumerable<Int32> in C# or IEnumerable(Of Int32) in Visual Basic that contains a range of sequential integral numbers.

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

Repeat

Type Parameters

TResult
The type of the value to be repeated in the result sequence.

Parameters

element
Type: TResult
The value to be repeated.
count
Type: System.Int32
The number of times to repeat the value in the generated sequence.

Return Value

Type: System.Collections.Generic.IEnumerable(Of TResult)
An IEnumerable(Of T) that contains a repeated value.

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

Empty

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

Any

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
The IEnumerable(Of T) to check for emptiness.

Return Value

Type: System.Boolean
true if the source sequence contains any elements; otherwise, false.

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

All

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
An IEnumerable(Of T) that contains the elements to apply the predicate to.
predicate
Type: System.Func(Of TSource, Boolean)
A function to test each element for a condition.

Return Value

Type: System.Boolean
true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

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

Count

Type Parameters

TSource
The type of the elements of source.

Parameters

source
Type: System.Collections.Generic.IEnumerable(Of TSource)
A sequence that contains elements to be tested and counted.
predicate
Type: System.Func(Of TSource, Boolean)
A function to test each element for a condition.

Return Value

Type: System.Int32
A number that represents how many elements in the sequence satisfy the condition in the predicate function.

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

Sum

#region 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)
    });
#endregion

Min

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

Max

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

Average

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

Aggregate

#region 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)
    });
#endregion

Posted By: Mr. Palash Paul

2 comments:

  1. Replies
    1. Hi, This is not the Right place for Adds... U should use ur own page or rent some one.
      This Page is for Knowledge sharing NOT for Idealistic Activity or Spamming....

      Delete