Object Initializing
class Program {
static void Main(string[] args) {
// create a new Phone object
ConfigPhone(new Phone {
ID = 1, Name = “HTC”,
Description = “Mobile Phone”,
Price = 500, Category = “Mobile Phone”
});
}
private static void ConfigPhone( Phone phoneParam) {
//…statements to config phone
}
}
Initializing Generics, Collections and Arrays
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
string[] strArray = { “HTC”, “IPhone”, “Nokia” };
List<int> intList = new List<int> { 10, 20, 30, 40 };
Dictionary<string, int> dict = new Dictionary<string, int> {
{ “HTC”, 100 },
{ “IPhone”, 500 },
{ “Nokia”, 800 }
};
}
}
Extension Methods
using System.Collections.Generic;
public class Catalog {
public List<Product> Products { get; set; }
}
public static class AppExtensionMethods {
public static decimal TotalPrices(this Catalog prodParam) {
decimal total = 0;
foreach (Product prod in prodParam.Products) {
total += prod.Price;
}
return total;
}
}
The this keyword in front of the first parameter marks TotalPrices as an extension method. The first parameter tells .NET which class the extension method can be applied to.
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
// create and populate Catalog
Catalog cart = new Catalog {
Products = new List<Product> {
new Product {Name = “Apple”, Price = 10},
new Product {Name = “Orange”, Price = 20},
new Product {Name = “Plam”, Price = 20},
new Product {Name = “PineApple”, Price = 30}
}
};
// get the total value of the products in the cart
decimal cartTotal = cart.TotalPrices();
Console.WriteLine(“Total: {0:c}”, cartTotal);
}
}
Lambda Expression
IEnumerable<Product> filteredProducts = products.Filter(prod =>
prod.Category == “Soccer” || prod.Price > 20);
And finally, if we need logic in the lambda expression that requires more than one statement, we can do so by using braces ({}) and finishing with a return statement, like this:
(prod, count) => {
//…multiple code statements
return result;
}
Automatic Type Inference
var myVariable = new Product { Name = “Milk”, Category = “Liquid”, Price = 10 };
string name = myVariable.Name;
The C# var keyword allows you to define a local variable without explicitly specifying the variable type. It is not that myVariable doesn’t have a type. It is just that we are asking the compiler to infer it from the code.
Anonymous Types
By combining object initializers and type inference, we can create simple data-storage objects without needing to define the corresponding class or struct.
var myProduct = new {
Name = “AUDI”,
Category = “CAR”
};
Console.WriteLine(“Name: {0}, Type: {1}”, myProduct.Name, myProduct.Category);
Language Integrated Queries (LINQ)
LINQ is a SQL-like syntax for querying data in classes.
Var results = from product in products
orderby product.price descending
Select new {product.Name, product.Price};
We order the Product objects in descending order and use the select keyword to return an anonymous type that contains just the properties we want. This style of LINQ is known as query syntax.
var results = products
.OrderByDescending(product => product.Price)
.Take(3)
.Select(product => new { product.Name, product.Price });
This style of LINQ is known as DOT notation syntax, Each of the LINQ extension methods is applied to an IEnumerable<T> and returns an IEnumerable<T>, which allows us to chain the methods together to form complex queries.The OrderByDescending method rearranges the items in the data source. In this case, the lambda expression returns the value we want used for comparisons. The Take method returns a specified number of items from the front of the results (this is what we couldn’t do using query syntax). The Select method allows us to project our results, specifying the result we want. In this case, we are projecting an anonymous object that contains the Name and Price properties. Notice that we have not even needed to specify the names of the properties in the anonymous type. C# has inferred this from the properties we picked in the Select method.
var result = products.Max(item1 => item1.price);
Gets the maximum priced product
