问题
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?
- 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; }
....
....
}
Controller:
....
....
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] ....)
{
....
....
}
}
}
回答1:
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) Use System.Reflection to obtain list of properties in your object (slow!)
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();
Your model will be List<object[]>
instead of List<MyViewModel>
3) Manually check required properties:
if (testlist[i].ManufCost ....)
来源:https://stackoverflow.com/questions/44377206/issue-on-looping-over-a-list-of-viewmodel-using-for-loop