Aggregate sum of all elements in array using LINQ
int[] numbers = new int[] {1,2,3,4,5,6,7,8}; int result = numbers.Sum(); Console.WriteLine(result);
Query processes using LINQ to find windows services
IEnumerable<Process> pList = from proc in Process.GetProcesses() where String.Equals(proc.ProcessName, "svchost") select proc;
Simple LINQ to Objects example
List<Employee> employees = new List<Employee>() { new Employee { ID=1, Name="Ravi", JoinDate=new DateTime(2002, 1, 15) }, new Employee { ID=2, Name="Raja", JoinDate=new DateTime(2002, 3, 17 }, new Employee { ID=3, Name="Mani", JoinDate=new DateTime(2007, 2, 11) } }; IEnumerable<Employee> query = from e in employees where e.JoinDate.Year < 2003 orderby e.Name select e; foreach (Employee e in query) { Console.WriteLine(e.Name); }
Employee Class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace W3mentorLinq { public class Employee { public int ID { get; set; } public string Name { get; set; } public DateTime JoinDate { get; set; } } }
Query public types in an assembly using LINQ
IEnumerable<string> publicTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsPublic select t.FullName; foreach (string name in publicTypes) { Console.WriteLine(name); }
Of Type example in C# LINQ
The default OfType
ArrayList MixedArray = new ArrayList(); foreach (var p in ProductList) MixedArray.Add(p); foreach (var c in CustomerList) MixedArray.Add(c); var query23 = from c in MixedArray.OfType < Customer > ().Cast < Customer > () where c.Country == “USA” orderby c.CompanyName select new { c.CustomerID, c.CompanyName }; foreach (var c in query23) sbResult.Append(String.Format(“CustomerID = {0}, CompanyName = {0}\r\n”, c.CustomerID, c.CompanyName));
Cast an ArrayList to an IEnumerable object
The following examples generate an ArrayList containing Customer elements and cast the ArrayList to an IEnumerable
ArrayList CustomersArray = new ArrayList(); foreach (var c in CustomerList) CustomersArray.Add(c); var query22 = from c in CustomersArray.Cast < Customer > () where c.Country == “USA” orderby c.CompanyName select new { c.CustomerID, c.CompanyName }; foreach (var c in query22) sbResult.Append(String.Format(“CustomerID = {0}, CompanyName = {0}\r\n”, c.CustomerID, c.CompanyName));
Left outer join example in LINQ C#
The following examples implement a left outer join of Customer with Order objects with default values supplied to display Customer objects that don’ t have corresponding Order objects.
// Populate the default order instance Order emptyOrder = new Order { OrderID = 0, CustomerID = “XXXXX”, EmployeeID = 0, OrderDate = DateTime.Parse(“1/1/1900”), RequiredDate = DateTime.Parse(“1/1/1900”), ShipVia = 0, Freight = 0M, ShipName = “Default Order” }; var query11 = from c in CustomerList where c.Country == “USA” join o in OrderList on c.CustomerID equals o.CustomerID into co from d in co.DefaultIfEmpty(emptyOrder) select new { c, d }; foreach (var c in query11) sbResult.Append(String.Format(“CustID = {0}, Name = {1}, OrderID = {2}, OrderDate = {3:d}\r\n”, c.c.CustomerID, c.c.CompanyName, c.d.OrderID, c.d.OrderDate));
We will encounter runtime errors if your inner object has non – nullable value types and we donot provide a
default instance populated with default values as the DefaultIfEmpty operator’s argument.
Sort on multiple criteria with orderby using LINQ C#
using System; using System.Linq; class Account { public string FirstName { get; private set; } public string LastName { get; private set; } public double Balance { get; private set; } public string AccountNumber { get; private set; } public Account(string fn, string ln, string accnum, double b) { FirstName = fn; LastName = ln; AccountNumber = accnum; Balance = b; } } class OrderbyDemo { static void Main() { // Create some data. Account[] accounts = { new Account("Madhu", "Ma", "1321K", 200.23), new Account("Mani", "Pan", "1234D", 6000.00), new Account("Item", "Raja", "335D", 3923.85), new Account("Kunk", "Lmesh", "23M44", 187.132), }; // Create a query that obtains the accounts in sorted order. // Sorting first by last name, then within same last names sorting by // by first name, and finally by account balance. var accInfo = from acc in accounts orderby acc.LastName, acc.FirstName, acc.Balance select acc; Console.WriteLine("Accounts in sorted order: "); string str = ""; // Execute the query and display the results. foreach(Account acc in accInfo) { if(str != acc.FirstName) { Console.WriteLine(); str = acc.FirstName; } Console.WriteLine("{0}, {1}\tAcc#: {2}, {3,10:C}", acc.LastName, acc.FirstName, acc.AccountNumber, acc.Balance); } Console.WriteLine(); } }
Use orderby to retrieve the values in an int array in ascending order in LINQ
using System; using System.Linq; class OrderbyDemo { static void Main() { int[] nums = { 10, -19, 4, 7, 2, -5, 0 }; // Create a query that obtains the values in sorted order. var posNums = from n in nums orderby n select n; Console.Write("Values in ascending order: "); // Execute the query and display the results. foreach(int i in posNums) Console.Write(i + " "); Console.WriteLine(); } }
Values in ascending order: -19 -5 0 2 4 7 10
LINQ where clause with substrings
using System; using System.Linq; class WhereDemo2 { static void Main() { string[] strs = { ".com", ".net", "someNameA.com", "someNameB.net", "test", ".network", "someNameC.net", "someNameD.com" }; // Create a query that obtains Internet addresses that // end with .net. var netAddrs = from addr in strs where addr.Length > 4 && addr.EndsWith(".net") select addr; // Execute the query and display the results. foreach(var str in netAddrs) Console.WriteLine(str); } }
The output:
someNameB.net
someNameC.net
Use multiple where clauses in LINQ C#
using System; using System.Linq; class TwoWheres { static void Main() { int[] nums = { 1, -2, 3, -3, 0, -8, 12, 19, 6, 9, 10 }; // Create a query that obtains positive values less than 10. var posNums = from n in nums where n > 0 where n < 10 select n; Console.Write("The positive values less than 10: "); // Execute the query and display the results. foreach(int i in posNums) Console.Write (i + " "); Console.WriteLine(); } }
The positive values less than 10: 1 3 6 9
Intersect operator in C# LINQ
The Intersect SQO returns a sequence of elements that the first and second sequences contain; its method signature is the same as Union’s except for the method name.
var query19 = (from p in ProductList where p.CategoryID == 1 || p.CategoryID == 2 select p) .Intersect(from p in ProductList where p.CategoryID == 2 || p.CategoryID == 3 select p) .OrderBy(p = > p.ProductName); foreach (var p in query19) sbResult.Append(String.Format(“CategoryID = {0}, ProductID = {1}, “ + ProductName = {2}\r\n”, p.CategoryID, p.ProductID, p.ProductName));
Union operator in C# LINQ
The Union SQO combines two sequences of the same structure into one without regard to matching values.
var query18 = (from c in CustomerList join s in SupplierList on c.City equals s.City select new { c.City, c.CompanyName, Type = “Customer” }) .Union(from c in CustomerList join s in SupplierList on c.City equals s.City select new { s.City, s.CompanyName, Type = “Supplier” }) .OrderBy(c = > c.City) .ThenBy(c = > c.CompanyName); // Append list head sbResult.Append(“City\tCompany Name\t\tRelationship\r\n”); // Append query results foreach (var u in query18){ string strFormat = “{0}\t{1}\t”; if (u.CompanyName.Length < 20) strFormat += “\t”; strFormat += “{2}\r\n”; sbResult.Append(string.Format(strFormat, u.City, u.CompanyName, u.Type)); }
Distinct Set Operator in C# LINQ
The Distinct SQO removes elements with duplicate values from a sequence. The following example returns a list of unique country names from the CustomerList collection’s Country field.
var query17 = (from c in CustomerList orderby c.Country select c.Country).Distinct(); foreach (var c in query17) sbResult.Append(String.Format(“Country = {0}\r\n”, c));
Example of GroupBy with Query Expression Syntax in C# LINQ
var query16 = from c in CustomerList orderby c.Country, c.CustomerID group c by c.Country into g select new { Country = g.Key, Group = g }; foreach (var g in query16) { sbResult.Append(g.Group + “\r\n”); foreach (var c in g.Customer) sbResult.Append(String.Format( CustomerID = {0}, CompanyName = {1}, “ + “City = {2}/r/n”, c.CustomerID, c.CompanyName, c.City)); }
Example of GroupBy with Method Call Syntax in C# LINQ
var query15 = CustomerList.GroupBy(c = > c.Country); query15 = CustomerList.OrderBy(c = > c.Country) .ThenBy(c = > c.CustomerID) .GroupBy(c = > c.Country); foreach (var g in query15) { sbResult.Append(g.Key + “\r\n”; foreach (var c in g) sbResult.Append(String.Format(“ CustomerID = {0}, CompanyName = {1}, “ + “City = {2}\r\n, c.CustomerID, c.CompanyName, c.City)); }
OrderBy using CurrentCultureIgnoreCase in C# LINQ
var query14 = ProductList.Where(p = > p.Category.CategoryName == “Beverages”) .OrderBy(p = > p.ProductName, StringComparer.CurrentCultureIgnoreCase); foreach (var p in query14) sbResult.Append(String.Format(“ProductID = {0}, UnitPrice = {1:c}, “ & “Name = {2}\r\n”, p.ProductID, p.UnitPrice, p.ProductName));
ThenBy and ThenByDescending example in LINQ
var query13 = ProductList.OrderBy(p = > p.CategoryID) .ThenByDescending(p = > p.UnitPrice) .ThenBy(p = > p.ProductName); query13 = from p in ProductList orderby p.CategoryID, p.UnitPrice descending, p.ProductName select p; foreach (var p in query13) sbResult.Append(String.Format(“CategoryID = {0}, UnitPrice = {1:c}, “ + Name = {2}\r\n”, p.CategoryID, p.UnitPrice, p.ProductName));
Concat operator example in C# LINQ
var Query12 = CustomerList.Where(c = > c.Country == “USA”) .Concat(CustomerList.Where(c = > c.Country == “Canada”) .Concat(CustomerList.Where(c = > c.Country == “Mexico”))); Query12 = (from c in CustomerList where c.Country == “USA” select c) .Concat((from c in CustomerList where c.Country == “Canada” select c) .Concat((from c in CustomerList where c.Country == “Mexico” select c))); foreach (var c in Query12) sbResult.Append(String.Format(“CustID = {0}, Name = {1}, Country = {2}\r\n”, c.CustomerID, c.CompanyName, c.Country));
Examples of a left outer join in LINQ
The following examples implement a left outer join of Customer with Order objects with default values
supplied to display Customer objects that don ’ t have corresponding Order objects:
Order emptyOrder = new Order { OrderID = 0, CustomerID = “XXXXX”, EmployeeID = 0, OrderDate = DateTime.Parse(“1/1/1900”), RequiredDate = DateTime.Parse(“1/1/1900”), ShipVia = 0, Freight = 0M, ShipName = “Default Order” }; var query11 = from c in CustomerList where c.Country == “USA” join o in OrderList on c.CustomerID equals o.CustomerID into co from d in co.DefaultIfEmpty(emptyOrder) select new { c, d }; foreach (var c in query11) sbResult.Append(String.Format(“CustID = {0}, Name = {1}, OrderID = {2}, OrderDate = {3:d}\r\n”, c.c.CustomerID, c.c.CompanyName, c.d.OrderID, c.d.OrderDate));
