Converting an Array of Strings to Integers
using System;
using System.Linq;
public class MainClass {
public static void Main() {
string[] numbers = { "0042", "010", "9", "2q7" };
int[] nums = numbers.Select(s => Int32.Parse(s)).ToArray();
}
}
Converting an Array of Strings to Integers and Sorting It
using System;
using System.Linq;
public class MainClass {
public static void Main() {
string[] numbers = { "0042", "010", "9", "2q7" };
int[] nums = numbers.Select(s => Int32.Parse(s)).OrderBy(s => s).ToArray();
foreach (int num in nums)
Console.WriteLine(num);
}
}
Delegate targets
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class MainClass
{
public static void Main()
{
string[] currentVideoGames = {"Shooting", "D","Half Life", "F.E.A.R.","Game", "System"};
Func<string, bool> searchFilter = new Func<string, bool>(Filter);
Func<string, string> itemToProcess = new Func<string,string>(ProcessItem);
var subset = currentVideoGames.Where(searchFilter).OrderBy(itemToProcess).Select(itemToProcess);
foreach (var game in subset)
Console.WriteLine("Item: {0}", game);
}
public static bool Filter(string s) {return s.Length > 6;}
public static string ProcessItem(string s) { return s; }
}
Demonstrating the Query Results Changing Between Enumerations
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
int[] intArray = new int[] { 1, 2, 3 };
IEnumerable<int> ints = intArray.Select(i => i);
foreach (int i in ints)
Console.WriteLine(i);
intArray[0] = 5;
foreach (int i in ints)
Console.WriteLine(i);
}
}
Query Reuse
using System;
using System.Linq;
static class QueryReuse {
static double Square(double n) {
Console.WriteLine("Computing Square(" + n + ")...");
return Math.Pow(n, 2);
}
public static void Main() {
int[] numbers = { 1, 2, 3 };
var query =
from n in numbers
select Square(n);
foreach (var n in query)
Console.WriteLine(n);
for (int i = 0; i < numbers.Length; i++)
numbers[i] = numbers[i] + 10;
foreach (var n in query)
Console.WriteLine(n);
}
}
Query with Intentional Exception Deferred Until Enumeration
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] strings = { "one", "two", null, "three" };
Console.WriteLine("Before Where() is called.");
IEnumerable<string> ieStrings = strings.Where(s => s.Length == 3);
Console.WriteLine("After Where() is called.");
foreach (string s in ieStrings) {
Console.WriteLine("Processing " + s);
}
}
}
Returning a List
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
int[] intArray = new int[] { 1, 2, 3 };
List<int> ints = intArray.Select(i => i).ToList();
foreach (int i in ints)
Console.WriteLine(i);
intArray[0] = 5;
foreach (int i in ints)
Console.WriteLine(i);
}
}
Select all from a List
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;
class Car
{
public string PetName;
public string Color;
public int Speed;
public string Make;
public override string ToString()
{
return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}", Make, Color, Speed, PetName);
}
}
class Program
{
static void Main(string[] args)
{
Car[] myCars = new[]{
new Car{ PetName = "A", Color = "Silver", Speed = 100, Make = "BMW"},
new Car{ PetName = "B", Color = "Black", Speed = 55, Make = "VW"},
new Car{ PetName = "C", Color = "White", Speed = 43, Make = "Ford"}
};
var subset = from c in myCars select c;
foreach (var c in subset)
{
Console.WriteLine(c.ToString());
}
}
}
Select array item by type
using System;
using System.Linq;
static class TestArray {
static void Main() {
Object[] array = { "String", 12, true, "a" };
var types =
array
.Select(item => item.GetType().Name)
.OrderBy(type => type);
}
}
Select Distinct
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Customer
{
public string ID { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public decimal Sales { get; set; }
public override string ToString()
{
return "ID: " + ID + " City: " + City + " Country: " + Country + " Region: " + Region + " Sales: " + Sales;
}
}
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer> {
new Customer { ID="Q", City="London", Country="UK", Region="Europe", Sales=8000 },
new Customer { ID="R", City="Beijing", Country="China", Region="Asia", Sales=9000 },
new Customer { ID="T", City="Lima", Country="Peru", Region="South America", Sales=2002 }
};
var queryResults = customers.Select(c => c.Region).Distinct();
foreach (var item in queryResults)
{
Console.WriteLine(item);
}
}
}
Select only pet name
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;
class Car
{
public string PetName;
public string Color;
public int Speed;
public string Make;
public override string ToString()
{
return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}",Make, Color, Speed, PetName);
}
}
class Program
{
static void Main(string[] args)
{
Car[] myCars = new []{
new Car{ PetName = "A", Color = "Silver", Speed = 100, Make = "BMW"},
new Car{ PetName = "B", Color = "Black", Speed = 55, Make = "VW"},
new Car{ PetName = "C", Color = "White", Speed = 43, Make = "Ford"}
};
var names = from c in myCars select c.PetName;
foreach (var n in names)
{
Console.WriteLine("Name: {0}", n);
}
}
}
Select sum value
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; }
}
class Department
{
public string Name { get; set; }
List<Employee> employees = new List<Employee>();
public IList<Employee> Employees
{
get { return employees; }
}
}
class Company
{
public string Name { get; set; }
List<Department> departments = new List<Department>();
public IList<Department> Departments
{
get { return departments; }
}
}
class SalaryReport
{
static void Main()
{
var company = new Company
{
Name = "A",
Departments =
{
new Department
{
Name = "Development",
Employees =
{
new Employee { Name = "T", Salary = 75000m },
new Employee { Name = "D", Salary = 45000m },
new Employee { Name = "M", Salary = 150000m }
}
},
new Department
{
Name = "Marketing",
Employees =
{
new Employee { Name = "Z", Salary = 200000m },
new Employee { Name = "X", Salary = 120000m }
}
}
}
};
var query = company.Departments
.Select(dept => new { dept.Name, Cost = dept.Employees.Sum(person => person.Salary) })
.OrderByDescending(deptWithCost => deptWithCost.Cost);
foreach (var item in query)
{
Console.WriteLine(item);
}
}
}
Select with Anonymous Types: iterates over each element to print the element"s name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
int[] numbers = { 5, 4, 1};
string[] strings = { "zero", "one", "two"};
var digitOddEvens =
from n in numbers
select new { Digit = strings[n], Even = (n % 2 == 0) };
foreach (var d in digitOddEvens) {
Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
}
}
}
Select with Anonymous Types: prints the name of every product in the product list along with the category of the product and its unit price
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
List<Product> products = GetProductList();
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
Console.WriteLine("Product Info:");
foreach (var productInfo in productInfos) {
Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price);
}
}
static List<Product> GetProductList() {
List<Product> empTree = new List<Product>();
empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
return empTree;
}
}
class Product : IComparable<Product> {
public string ProductName { get; set; }
public string Category { get; set; }
public int UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public int Total { get; set; }
public DateTime OrderDate { get; set; }
public int Id { get; set; }
public override string ToString() {
return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
}
int IComparable<Product>.rupareTo(Product other) {
if (other == null)
return 1;
if (this.Id > other.Id)
return 1;
if (this.Id < other.Id)
return -1;
return 0;
}
}
Select with Anonymous Types: prints uppercase and lowercase versions of each string in an input array
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
string[] words = { "Abc", "aBc", "AAA" };
var upperLowerWords =
from w in words
select new { Upper = w.ToUpper(), Lower = w.ToLower() };
foreach (var ul in upperLowerWords) {
Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
}
}
}
Transformation: link two array.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
int[] numbers = { 5, 4, 1};
string[] strings = { "zero", "one", "two"};
var textNums =
from n in numbers
select strings[n];
Console.WriteLine("Number strings:");
foreach (var s in textNums) {
Console.WriteLine(s);
}
}
}
Use LINQ to query characters in a string
using System;
using System.Collections.Generic;
using System.Linq;
static class TestString {
static void Main() {
var count =
"abc 8"
.Where(c => !Char.IsLetter(c))
.Count();
Console.WriteLine(count);
}
}
Use LINQ with Dictionary
using System;
using System.Collections.Generic;
using System.Linq;
static class TestDictionary {
static void Main() {
Dictionary<int, string> frenchNumbers;
frenchNumbers = new Dictionary<int, string>();
frenchNumbers.Add(0, "zero");
frenchNumbers.Add(1, "one");
frenchNumbers.Add(2, "two");
frenchNumbers.Add(3, "three");
frenchNumbers.Add(4, "four");
var evenFrenchNumbers =
from entry in frenchNumbers
where (entry.Key % 2) == 0
select entry.Value;
}
}
Using select to create a sequence of each product name.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
List<Product> products = GetProductList();
var productNames =
from p in products
select p.ProductName;
foreach (var productName in productNames) {
Console.WriteLine(productName);
}
}
static List<Product> GetProductList() {
List<Product> empTree = new List<Product>();
empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
return empTree;
}
}
class Product : IComparable<Product> {
public string ProductName { get; set; }
public string Category { get; set; }
public int UnitPrice { get; set; }
public int UnitsInStock { get; set; }
public int Total { get; set; }
public DateTime OrderDate { get; set; }
public int Id { get; set; }
public override string ToString() {
return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
}
int IComparable<Product>.rupareTo(Product other) {
if (other == null)
return 1;
if (this.Id > other.Id)
return 1;
if (this.Id < other.Id)
return -1;
return 0;
}
}