Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何访问foreach列表中的属性_C#_List - Fatal编程技术网

C# 如何访问foreach列表中的属性

C# 如何访问foreach列表中的属性,c#,list,C#,List,我创建的对象中包含一些属性。所以对于这个对象,我将在从数据库查询后添加值 之后,我需要进行分组和求和。所以我会这样做: var after_grouping = from t in list_item group t by new {t.category_subcategory,t.item} into g select new { no = g.Key,

我创建的对象中包含一些属性。所以对于这个对象,我将在从数据库查询后添加值

之后,我需要进行分组和求和。所以我会这样做:

var after_grouping = from t in list_item
                    group t by new {t.category_subcategory,t.item} into g
                    select new {
                        no = g.Key,
                        price = g.Sum(a=>a.price),
                        quantity = g.Sum(a=>a.quantity)

                    };
然后我需要将“after_grouping”中的值添加到新对象类中。因此,我将在分组后在变量中执行foreach

 foreach(PropertyInfo eachRow in after_grouping.GetType().GetProperties())
        { 
            string cat_sub = "";
            string item_name = "";
            decimal price = 0;
            decimal quantity = 0;
            decimal total = 0;  
            //Access the object here

            listAfterCopy.Add(new SelectedItemOnPoCopy(cat_sub, item_name, price, quantity, total));

        }
我的问题是,如何访问我在变量“after_grouping”中创建的属性


如果你有更好的建议,请告诉我。

你不需要思考就可以做到这一点。可以使用与自定义类相同的方式访问匿名类型属性:

foreach(var item in after_grouping)
{ 
    listAfterCopy.Add(
        new SelectedItemOnPoCopy(
            item.no.category_subcategory,
            item.no.item,
            item.price,
            item.quantity
        )
    );
}

为什么在循环构造中调用
GetType
GetProperties
?通过这样做,您将遍历您先前创建的匿名类型的反射属性,而不是集合中该类型的实例。@PrestonGuillot,对不起,我的错,我认为这是正确的方法。噢,谢谢你,伙计。对不起,在这之前我不太明白。我认为仍然需要进行反射才能访问该属性。