2014年4月29日 星期二

使用匿名方法賦值給匿名類別的屬性

好繞口... 

以北風資料庫的Products table 為例,假設我想做一個某家供應商的產品List,並把價格提高10%,於是我這麼寫...
var v = from product in dtNorthwindProduct.AsEnumerable()
        where product.Field<int>("SupplierID") == 1
        select new
        {
            pid = product.Field<int>("ProductID"),
            //以匿名方法重新計算價格
            price = () =>{ return product.Field<decimal>("UnitPrice") * 1.1M }
        };
.NET很乾脆地給我錯誤...

因為初始匿名型別的屬性有兩個限制
  1. 不能是null
  2. 不能用匿名方法賦值
所以要這麼寫...
var v = from product in dtNorthwindProduct.AsEnumerable()
        where product.Field<int>("SupplierID") == 1
        select new
        {
            pid = product.Field<int>("ProductID"),
            //以匿名方法重新計算價格
            price = new Func<decimal>(() => { return product.Field<decimal>("UnitPrice") * 1.1M; }).Invoke()
        };
就可以了...

參考連結
C#/.NET Little Wonders: The Joy of Anonymous Types
Assigning property of anonymous type via anonymous method