Search This Blog

2009-06-03

C# 3.0 Tutorial -7:Projections

Projections

There is one final feature of anonymous types to point out, and until you see Linq this is going to feel a little obscure. So far we have declared a field in an anonymous type by specifying its name and initializing it to a value. There are two other ways.

The first is to simply write the name of an already declared variable. The name of the variable will be taken as the name of the field, and the value it holds will be used to initialize the field. Using this, you could rewrite:
var x = new {
Real = 5.4,
Complex = 2.8
};As:
var Real = 5.4;
var Complex = 2.8;
var x = new {
Real,
Complex
};
In this case it complicates the code, but it's worth being aware of. There is a variation on this where instead of naming a variable, you access a member of an existing object. The field takes the name and value of the member.

Imagine we have a class called Customer that represents all of the details of a customer, but we just want an anonymous type that contains the name and email address. We can write the following:

Customer c = GetCustomer(1764);
var EmailRecord = new { c.Name, c.Email };This is equivalent to:
Customer c = GetCustomer(1764);
var EmailRecord = new {
Name = c.Name,
Email = c.Email
};

tags:what is projections in c# 3.0 /3.5

No comments: