Issue on looping over a list of ViewModel using for loop

喜你入骨 提交于 2019-12-13 09:17:56

问题


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?

  1. Error at inner loop for (var j = 0; j < testlist[i].Count(); j++){...}: MyViewModel does not contain a definition of Count()
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!