1

我的应用程序是使用实体框架的 asp.net MVC3。我正在尝试使用以下方法从表中获取一列的列表作为数组:

   public ActionResult Index()
        {
            //var list = db.CasesProgresses.ToList();
            var SeriesList = GetSeriesList(Learner_ID);
            return View();
        }



        public List<string> GetSeriesList(string item)
        {
            // get DataTable dt from somewhere.
            List<string> sList = new List<string>();
            foreach (CasesProgress row in db.CasesProgresses)
            {
                sList.Add(row[0].ToString());
            }
            return sList;  
        }

我收到两个错误:

Cannot apply indexing with [] to an expression of type 'caseprog.Models.CasesProgress' and
The name 'Learner_ID' does not exist in the current context

将不胜感激您的建议。

4

4 回答 4

3

您可能需要阅读CasesProgress对象的属性名称

改变这个

sList.Add(row[0].ToString());

sList.Add(row.YourPropertyNameHereWhichIsOfStringType);

如果属性不是字符串类型(例如:整数/小数),您可以对其应用ToString()方法,然后添加到字符串集合中。

sList.Add(row.Learner_ID.ToString());

假设Learner_IDCasesProgress具有数字类型的类的属性。

于 2012-09-20T19:04:20.757 回答
1
 foreach (CasesProgress row in db.CasesProgresses)
 {
   sList.Add(row.SomePropertyYouNeed.ToString());
 }

如果您使用的是 foreach,则没有[0]. 如果您使用的是普通的for (int i =0; i < list.Count; i ++;),那么您将能够做到这一点。但是当然,您必须将 更改0i,并且您仍然需要访问属性。好吧,如果您的 List 具有不同的类型,您就不必这样做,但在您当前的示例中,您将需要添加一个字符串。

于 2012-09-20T19:04:30.673 回答
1
The name 'Learner_ID' does not exist in the current context 
GetSeriesList(Learner_ID);

Learner_ID - 未在您的操作中定义,您可以将其删除,因为未使用 GetSeriesList(string item) 中的参数(也删除参数)。

Cannot apply indexing with [] to an expression of type 'caseprog.Models.CasesProgress'

行中foreach是与集合分开的项目,这就是为什么你应该通过带有点符号的属性来访问它row.Property

于 2012-09-20T19:07:47.627 回答
0

为什么不保持简单并使用“通常”的语法


var list = db.CasesProgresses.Select(o=>o.YourPropertyName).ToList();

如果它是一个 int 并且您需要它作为字符串列表,只需将 YourPropertyName 替换为上面的 YourPropertyName.ToString()

于 2012-09-20T19:39:52.707 回答