[英]MVC Entity Framework get one column as an array
我的應用程序是使用實體框架的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
感謝您的建議。
您可能需要讀取CasesProgress
對象的屬性名稱
改變這個
sList.Add(row[0].ToString());
至
sList.Add(row.YourPropertyNameHereWhichIsOfStringType);
如果該屬性不是字符串類型( 例如:Integer / decimal ),則可以對此應用ToString()
方法,然后將其添加到字符串集合中。
sList.Add(row.Learner_ID.ToString());
假設Learner_ID
是具有數字類型的CasesProgress
類的屬性。
foreach (CasesProgress row in db.CasesProgresses)
{
sList.Add(row.SomePropertyYouNeed.ToString());
}
如果您使用的是foreach,則沒有[0]
。 如果您for (int i =0; i < list.Count; i ++;)
使用法線for (int i =0; i < list.Count; i ++;)
則可以做到這一點。 但是,當然,您必須將0
更改為i
,並且仍然需要訪問屬性。 那么你就不必這樣做,如果你的列表有不同的類型,但在當前的例子中,你將需要添加一個字符串。
The name 'Learner_ID' does not exist in the current context
GetSeriesList(Learner_ID);
Learner_ID-未在您的操作中定義,您可以刪除它,因為未使用GetSeriesList(字符串項目)中的參數(也刪除了參數)。
Cannot apply indexing with [] to an expression of type 'caseprog.Models.CasesProgress'
在foreach
行中,集合中有單獨的項目,這就是為什么您應該通過屬性使用點符號row.Property
訪問它。
為什么不只是保持簡單並使用“常規”語法
var list = db.CasesProgresses.Select(o=>o.YourPropertyName).ToList();
如果它是一個int,並且您需要它作為字符串列表,則只需用上方的YourPropertyName.ToString()替換YourPropertyName
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.