这种匿名类型如何在现实生活中发挥作用?为什么匿名是好事?
// sampleObject is an instance of a simple anonymous type.
var sampleObject =
new { FirstProperty = "A", SecondProperty = "B" };
请您参考如下方法:
来自 MSDN Anonymous Types (C# Programming Guide) :
Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.
...
The most common scenario is to initialize an anonymous type with properties from another type.
更多信息,您可以阅读 Anonymous Types in Query Expressions .
此外,请考虑阅读 SO What is the purpose of anonymous types?
考虑来自 How to: Join by Using Composite Keys (C# Programming Guide) 的示例:
var query = from o in db.Orders
from p in db.Products
join d in db.OrderDetails
on new { o.OrderID, p.ProductID }
equals new { d.OrderID, d.ProductID }
into details
from d in details
select new { o.OrderID, p.ProductID, d.UnitPrice };
This example shows how to perform join operations in which you want to use more than one key to define a match. This is accomplished by using a composite key. You create a composite key as an anonymous type or named typed with the values that you want to compare.
以及使用匿名类型对 dara 进行分组以封装包含来自 Group by Multiple Columns using Anonymous Types in LINQ to SQL 的多个值的键的示例:
var months = from t in db.TransactionData
group t by new { month = t.Date.Month, year = t.Date.Year }
into d
select new { t.Key.month, t.Key.year };
或更好How to: Group Query Results (C# Programming Guide) :
An anonymous type is used because it is not necessary to use the complete object to display the results
Note that the properties in the anonymous type become properties on the Key member and can be accessed by name when the query is executed.
