你沒有說明你的問題的上下文,所以我會回答LinqToObjects和LinqToSql。
在LinqToObjects中,假設您有一個List<Customer> source
。
//Straight projection.
//no new instances are created when query is evaluated.
IEnumerable<Customer> result =
from c in source where c.Name == "Bob"
select c;
//Different Type projection
//a new instance of CustomerName is created
// for each element in the result when the query is evaluated.
IEnumerable<CustomerName> result =
from c in source where c.Name == "Bob"
select new CustomerName() {Name = c.Name};
//Anonymous Type Projection
//a new instance of an anonymous type is created
// for each element in the result when the query is evaluated.
//You don't have access to the type's name
// since the compiler names the type,
// so you must use var to talk about the type of the result.
var result =
from c in source where c.Name == "Bob"
select new {Name = "Bob"};
//Tuple Projection (same as Different Type Projection)
//a new instance of Tuple is created
// for each element in the result when the query is evaluated.
IEnumerable<Tuple<string, int>> result =
from c in source where c.Name == "Bob"
select new Tuple<string, int>(){First = c.Name, Second = c.Id};
在LinqToSql,假設你有一個IQueryable<Customer> db.Customers
//Straight projection
//when the query is resolved
// DataContext.Translate<Customer> is called
// which converts the private dbReader into new Customer instances.
IQueryable<Customer> result =
from c in db.Customers where c.Name == "Bob"
select c;
//Different Type Projection
//when the query is resolved
// DataContext.Translate<CustomerName> is called
// which converts the private dbReader into new CustomerName instances.
// 0 Customer instances are created.
IQueryable<Customer> result =
from c in db.Customers where c.Name == "Bob"
select new CustomerName() {Name = c.Name};
//Different Type Projection with a twist
//when the query is resolved
// DataContext.Translate<CustomerGroup> is called
// which converts the private dbReader into new CustomerGroup instances.
// 0 Customer instances are created.
//the anonymous type is used in the query translation
// yet no instances of the anonymous type are created.
IQueryable<Customer> result =
from c in db.Customers
group c by new {c.Name, TheCount = c.Orders.Count()} into g
select new CustomerGroup()
{
Name = g.Key.Name,
OrderCount = g.Key.TheCount,
NumberInGroup = g.Count()
};
好吧,那現在夠了。
我使用linq2entities,所以我覺得它就像你的第一個例子。 對匿名使用元組有什麼原因或好處? – punkouter 2010-06-13 16:00:43
匿名類型的實例不會很好地跨越方法邊界。元組沒有這個問題。 – 2010-06-13 16:46:50
但基本情況下,在快速linq查詢中發回一個對象而無需定義一個新類,我猜這就是anon類型的全部要點。 – punkouter 2010-06-14 15:08:57