Wednesday, September 24, 2008

Anonymous Type

Anonymous Type

var query = from c in ctx.Customers
where (c.City=="Toronto")
select new {
Name = c.ContactName,
Address = c.Address
ConstVal = "constant value",
Calculated = C.ContactName + C.Address
}


foreach (ver item in query)
{
Console.Writeline("User name: {0}, address:{1}, const:{2}", item.ContactName, item.Address, item.ConstVal);
}

when access an anonymous type object, the compiler understand from context of the types and determine the data type from the value.
that explains why var can only be a local variable.

but, there is a little bit wonder about the following code. how to access the members?

var q = from c in Customers
join o in Orders on c.ID equals o.CustomerID
where c.FirstName == "Wes"
orderby o.Date
select new { c.Lastname, o };




Lamdas

all lamda expressions have the form:
(parameters) => expression

e.g.
(x, y)=>x+y;
or
(int x, int y)=>x==y;

lamda expression is a anonymous delegate or anonymouse function. it can be used anywhere a delegate can be used.

public delegate T myfunc(T1 x,T2 y);


An example of anonymous delegate:

public static void PrintMatchingNumbers(int from, int to, NumberTester filter)
{
...
}

public static void caller()
{
PrintMatchingNumbers(1, 10,
delegate(int i)
{
return (i % d) == 0;
});

}

It creates an delegate instance on the fly.

Func<> and Expression<>

Func is a delegate type of generic function.

Func nonExprLambda = x => (x & 1) == 0;



MethodInfo method = typeof(Mock).GetMethod("PublicMethodParameters",
newType[] { typeof(string), typeof(int) }));


MethodInfo info = Reflector.Method(
(x, y, z) => x.PublicMethodParameters(y, z));


lamda expression is Expression generic type. It can be used to declare vars and assign a lamda expression value to it.
Expression> exprLambda = x => (x & 1) == 0;




Reference:

http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees
http://msdn.microsoft.com/en-us/library/bb397687.aspx
Strong Typed Reflection, http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1273739,00.html

No comments: