向Linq结果集对象添加动态属性

时间:2013-07-15 01:46:17

标签: linq dynamic

我有对象列表:

List<dynamic> prods = new List<dynamic>();

            foreach (DataRow row in dataTable.Rows)
            {
                dynamic obj = new ExpandoObject();
                IDictionary<string, object> oprops = obj;

                foreach (System.Data.DataColumn col in dataTable.Columns)
                    oprops.Add(col.ColumnName, row[col.ColumnName]);
                obj = oprops;
                list.Add(obj);
            }

pricing列表的填充方式与DataTable产品定价相同。

我有这个问题:

var result = (from product in prods join price in pricing on product.ID equals price.ProductID select new { product, price }).ToList();

我想在结果集中添加更多属性。

    foreach (dynamic obj in q)
    {
        obj.Test = "yes, testing."; // This line gives runtime error
        Console.WriteLine(
            "{0} - {1}",
            obj.product.Name,
            obj.price.UnitPrice);
    }

我还有一些对象/值要添加到foreach循环中的每个单独的结果对象中。

我无法做到这一点,因为它会抛出运行时错误,如下所示:

<>f__AnonymousType1<dynamic,dynamic>' does not contain a definition for 'Test' and no extension method 'Test' accepting a first argument of type '<>f__AnonymousType1<dynamic,dynamic>' could be found (are you missing a using directive or an assembly reference?)

2 个答案:

答案 0 :(得分:0)

在查询数据时添加属性,以便在foreach循环中设置;例如:

var result = (from product in prods
                join price in pricing on product.ID equals price.ProductID
                select new { product, price, Test = (string)null, }
             ).ToList();

或者,我从未尝试过的东西,可能会使用ExpandoObject

var result = (from product in prods
                join price in pricing on product.ID equals price.ProductID
                select new ExpandoObject { product, price }
             ).ToList();

答案 1 :(得分:0)

所以,这就是我发现的,我们无法扩展linq查询结果集,但是创建一个新的exapndo对象解决了添加新属性的问题。

这实际上就是我所做的:

List<dynamic> list = new List<dynamic>();
            foreach (var o in q)
            {
                dynamic obj = new ExpandoObject();
                IDictionary<string, object> oprops = obj;
                oprops.Add("Test", "yes, testing!");
                oprops.Add("product", o.product);
                oprops.Add("price", o.price);
                obj = oprops;
                list.Add(obj);
            }