Csharp/CSharp Tutorial/LINQ/Projection
Projection Creates New Objects
<source lang="csharp">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="A", City="New York", Country="USA", Region="North America", Sales=9999}, 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 = from c in customers where c.Region == "Asia" select new { c.City, c.Country, c.Sales } ; foreach (var item in queryResults) { Console.WriteLine(item); } } }</source>
Projection Linq
<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ruponentModel;
public class Person { public int Age { get; set; } public string Name { get; set; } List<Person> friends = new List<Person>(); public List<Person> Friends { get { return friends; } } public Person() { } public Person(string name) { Name = name; } } class Projection { static void Main() { List<Person> family = new List<Person> { new Person {Name="H", Age=31}, new Person {Name="J", Age=31}, new Person {Name="T", Age=4}, new Person {Name="W", Age=1} }; var converted = family.ConvertAll(delegate(Person person) { return new { person.Name, IsAdult = (person.Age >= 18) }; } ); foreach (var person in converted) { Console.WriteLine("{0} is an adult? {1}", person.Name, person.IsAdult); } } }</source>
Projection Operators: do calculation in select statement
<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MainClass {
public static void Main() { int[] numbers = { 5, 4, 1, 3, 9}; var numsPlusOne = from n in numbers select n + 1; Console.WriteLine("Numbers + 1:"); foreach (var i in numsPlusOne) { Console.WriteLine(i); } }
}</source>