Introduction
In the previous article, I illustrated some of the C# 3.0 new language and compiler features. I'll illustrate the rest of the features in this second part.
- Implicitly Typed Local Variables and Arrays
- Object Initializers
- Collection Initializers
- Extension Methods
- Anonymous Types
- Lambda Expressions
- Query Keywords
- Auto-Implemented Properties
- Partial Method Definitions
In this article, I will define the last five features and provide code samples.
The C# compiler enables you to create a new type at runtime which is not available at the source code level. It encapsulates a set of read-only properties into a single object without having to first explicitly define a type. The type of the properties is inferred by the compiler which can create an anonymous type by using the properties in an object initializer.
For example, consider the following declaration:
var person = new { Name = "Mony Hamza", SSN = "12345678" };
Here, the compiler automatically creates an anonymous type and infers the types of the properties from the object initializer. It also creates the private
fields associated with these properties and the necessary set
and get
accessors. When the object is instantiated, the properties are set to the values specified in the object initializer.
Here is an example for declaring an anonymous type and displaying its content:
class MyClass
{
static void Main(string[] args)
{
var obj1 = new { Name = "Mony Hamza", SSN ="12345678" };
Console.WriteLine("Name: {0}\nSSN: {1}", obj1.Name,obj1.SSN);
Console.ReadLine();
}
}
Output:
Name: Mony Hamza
SSN: 12345678
I've received a question about why to use "implicitly typed variables". If you are to use an anonymous variable, then this variable must be initialized using the keyword var
. We also have to consider the following notes about Anonymous types:
- Anonymous types are reference types that derive directly from object. From the perspective of the common language runtime, an anonymous type is no different from any other reference types.
- If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.
- An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named
struct
or cla
ss
instead of an anonymous type.
- Anonymous types cannot contain unsafe types as properties.
- Because the
Equals
and GetHashCode
methods on anonymous types are defined in terms of the Equals
and GetHashcode
of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
Lambda expressions provide a concise syntax for writing anonymous methods that can contain expressions and statements, and can be used to create delegates. All lambda expressions use the lambda operator =>
, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x
is read "x
goes to x
times x
."
Using Anonymous Methods in C# 2.0
public delegate int MyDelegate(int n);
class AnonymouseMethods
{
static void Main()
{
MyDelegate delegObject1 = new MyDelegate(
delegate(int n) { return n * 10; }
);
Console.WriteLine("The value is: {0}", delegObject1(5));
}
}
Using Lambda Expressions in C# 3.0
public delegate int MyDelegate(int n);
class LambdaExpresion
{
static void Main()
{
MyDelegate Obj1= new MyDelegate(
delegate(int n) { return n * 10; }
);
Console.WriteLine("The value using an anonymous method is: {0}",
Obj1(5));
MyDelegate Obj2 = (int n) => n * 10;
Console.WriteLine("The value using a lambda expression is: {0}",
Obj2(5));
Console.ReadLine();
}
}
Output:
The value using an anonymous method is: 50
The value using a lambda expression is: 50
We also can use more than one parameter in a lambda expression:
public delegate int MyDelegate(int m, int n);
MyDelegate myDelegate = (x, y) => x * y;
Console.WriteLine("The product is: {0}", myDelegate(5, 4));
More Examples
The following example shows you how to select the number which when divided by two has a remainder of 1.
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
The following examples illustrate how to select the string
s which starts with the letter M
:
List < string > Names=new List < string >{"Mony","John","Liza"};
List < string > Filterd=Names.FindAll(name =>name.StartsWith("M"));
foreach(string i in Filterd)
{
Console.WriteLine(i);
}
Keywords:
from
clause
where
clause
select
clause
group
clause
into
orderby
clause
join
clause (Inner join
, Group join
, Left outer join
)
let
clause
To understand Query expressions well, examples are the perfect choice.
The following example illustrates how to select numbers less than 5 and when divided by two have a remainder of 0.
static void Main()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums = from num in numbers
where num < 5 && num % 2 == 0
select num;
foreach (int i in lowNums)
{
Console.Write(i + " ");
}
}
The following example is from MSDN which will select all the students and their scores greater than 90, in order to access the inner list of scores. We use compound from
clauses.
public class Student
{
public string LastName { get; set; }
public List < int > Scores {get; set;}
}
static void Main()
{
List < Student> students = new List < Student>
{
new Student {LastName="Omelchenko", Scores= new List < int> {97, 72, 81, 60}},
new Student {LastName="O'Donnell", Scores= new List < int> {75, 84, 91, 39}},
new Student {LastName="Mortensen", Scores= new List < int> {88, 94, 65, 85}},
new Student {LastName="Garcia", Scores= new List < int> {97, 89, 85, 82}},
new Student {LastName="Beebe", Scores= new List < int> {35, 72, 91, 70}}
};
var scoreQuery = from student in students
from score in student.Scores
where score > 90
select new { Last = student.LastName, score };
Console.WriteLine("scoreQuery:");
foreach (var student in scoreQuery)
{
Console.WriteLine("{0} Score: {1}", student.Last, student.score);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output:
scoreQuery:
Omelchenko Score: 97
O'Donnell Score: 91
Mortensen Score: 94
Garcia Score: 97
Beebe Score: 91
Perform Joins (this example is also from MSDN which shows how to perform cross join with and without conditions).
static void Main()
{
char[] upperCase = { 'A', 'B', 'C'};
char[] lowerCase = { 'x', 'y', 'z'};
var joinQuery1 =
from upper in upperCase
from lower in lowerCase
select new { upper, lower};
var joinQuery2 =
from lower in lowerCase
where lower != 'x'
from upper in upperCase
select new { lower, upper };
Console.WriteLine("Cross join:");
foreach (var pair in joinQuery1)
{
Console.WriteLine("{0} is matched to {1}", pair.upper, pair.lower);
}
Console.WriteLine("Filtered non-equijoin:");
foreach (var pair in joinQuery2)
{
Console.WriteLine("{0} is matched to {1}", pair.lower, pair.upper);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output:
Cross join:
A is matched to x
A is matched to y
A is matched to z
B is matched to x
B is matched to y
B is matched to z
C is matched to x
C is matched to y
C is matched to z
Filtered non-equijoin:
y is matched to A
y is matched to B
y is matched to C
z is matched to A
z is matched to B
z is matched to C
In the first query expression it selects the Upper
, Lower
so it matches each upper letter with all the lower ones. However, in the second filter example, it selects Lower
, Upper
so that it matches each lower letter with all the upper ones.
Using Group By
The group
clause returns a sequence of IGrouping Of (TKey, TElement))
objects that contain zero or more items that match the key value for the group.
The following example will make it clear:
static void Main()
{
string[] Names = { "Mony", "Hamza", "Marica", "John", "Adam", "Olivia" };
var NameGroups =
from name in Names
group name by name[0];
foreach (var name in NameGroups)
{
Console.WriteLine("Names that start with the letter '{0}':", name.Key);
foreach (var name in NameGroups)
{
Console.WriteLine(name);
}
}
}
Output:
Names that start with the letter 'M':
Mony
Marica
Names that start with the letter 'H':
Hamza
Names that start with the letter 'J':
John
Names that start with the letter 'A':
Adam
Names that start with the letter 'O':
Olivia
Now let's add a little modification to the query in the previous example:
var NameGroups =
from name in Names
group name by name[0];
orderby name[0]
The result will be:
Names that start with the letter 'A':
Adam
Names that start with the letter 'H':
Hamza
Names that start with the letter 'J':
John
Names that start with the letter 'M':
Mony
Names that start with the letter 'O':
Olivia
Using into
It can be used to create a temporary identifier to store the results of a group
, join
or select
clause into a new identifier. This identifier can itself be a generator for additional query commands.
static void Main()
{
string[] words = { "apples", "blueberries", "oranges", "bananas", "apricots"};
var wordGroups1 =
from w in words
group w by w[0] into fruitGroup
where fruitGroup.Count() >= 2
select new { FirstLetter = fruitGroup.Key,
Words = fruitGroup.Count() };
foreach (var item in wordGroups1)
{
Console.WriteLine(" {0} has {1} elements.", item.FirstLetter, item.Words);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output:
a has 2 elements.
b has 2 elements.
Join
Inner Join
namespace Joins
{
public class Department
{
public int ID{get; set;}
public string Name{get; set;}
}
public class Employee
{
public int ID{get; set;}
public string Name{get; set;}
public int DeptID{get; set;}
}
public void ManageJoin()
{
List < Department > Departments=new List < Department >
{new Department{ID=1, Name="Sales"},new Department
{ID=2,Name="Marketing"}};
List < Employees > Employees=new List < Employee >
{new Employee {ID=1,Name="Mony",DeptID=1},
new Employee{ID=2,Name="Tom",DeptID=2}};
var innerJoinQuery = from employee in Employees
join dept in Department on employee.DeptID equals dept.ID
select new { EmployeeName = employee.Name,
DeptName = dept.Name };
}
}
The previous example will return each employee name and the department name.
Group Join
A join
clause with an into
expression is called a group join
.
Left Outer Join
In a left outer join
, all the elements in the left source sequence are returned, even if no matching elements are in the right sequence. To perform a left outer join
, use the DefaultIfEmpty
method in combination with a group join
.
Let's modify the previous example to apply Left Outer Join
:
var LeftouterJoinQuery = from employee in Employees
join dept in Department on employee.DeptID equals dept.ID
select new { EmployeeName = employee.Name,
DeptName = dept.Name } into empgroup
select empgroup.DefaultIfEmpty(new
{ EmployeeName = employee.Name, DeptName =
"No Department"});
Now it selects all the employees including those who are not attached to department yet.
You can use Auto Implemented Properties when no Additional logic is required, but you have to declare both a get
and a set
accessor.
//Auto Implemented Properties are used in the previous example, you can check it.
A partial class
or struct
may contain a partial method. One part of the class
contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
Hope that I succeeded in making the C# 3.0 features quite clear.
Waiting for your feedback.