关于使用for循环遍历ViewModel列表的问题 [英] Issue on looping over a list of ViewModel using for loop
问题描述
在以下控制器中,我需要遍历List的每个元素。 MyVieModel具有相当多的属性(列),并且列表具有数千行。因此,为了简洁起见,我需要使用一个外部循环和一个内部循环。但是, VS2015
在控制器的以下几行抱怨。我该如何解决该问题?
In the following controller, I need to loop through each element of a List. MyVieModel has quite a number of attrubutes (columns) and the list has thousands of rows. So, for brevity I need to use an outer and an inner loop. But, the VS2015
is complaining at the following lines in the controller. How can I resolve the issue?
- 错误在内部循环
中,用于(var j = 0; j< testlist [i] .Count(); j ++){...}
:MyViewModel
不包含Count() - 错误在行
if(testlist [i] [j] ....){...}
:无法将[]索引应用于类型MyViewModel的扩展
- Error at inner loop
for (var j = 0; j < testlist[i].Count(); j++){...}
:MyViewModel
does not contain a definition of Count() - Error at line
if (testlist[i][j] ....){...}
: cannot apply indexing with [] to an extension of type MyViewModel
ViewModel :
public class MyViewModel
{
[Key]
public int ProductId { get; set; }
public float laborCost { get; set; }
public float ManufCost { get; set; }
public float Price { get; set; }
....
....
}
控制器:
....
....
var testlist = (qry to load MyViewModel).ToList();
for (var i = 0; i < testlist.Count; i++)
{
for (var j = 0; j < testlist[i].Count(); j++)
{
if (testlist[i][j] ....)
{
....
....
}
}
}
推荐答案
在您的代码中, testlist [i]
是 MyViewModel
类的实例。您不能简单地通过for / foreach循环遍历其所有成员(属性,方法等)。
In your code testlist[i]
is an instance of MyViewModel
class. You can't simply iterate over all it's members (properties, methods etc) with a for/foreach loop.
1)使用System.Reflection获取以下位置的属性列表您的对象(慢!)
1) Use System.Reflection to obtain list of properties in your object (slow!)
2)从所需属性值手动创建数组
2) Manually make array from required property values
var testlist = (qry to load MyViewModel)
.Select(x => new object[] { x.ProductId, x.laborCost, x.ManufCost ...})
.ToList();
您的模型将是 List< object []>
而不是 List< MyViewModel>
3)手动检查所需属性:
3) Manually check required properties:
if (testlist[i].ManufCost ....)
这篇关于关于使用for循环遍历ViewModel列表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!