0

我有对象列表:

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?)
4

2 回答 2

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);
            }
于 2013-07-15T02:26:26.220 回答
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();
于 2013-07-15T01:55:11.627 回答