[英]C#: Return IEnumerable when field is not null?
public IEnumerable GetAddress()
{
DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students"));
DataTable dt = ds.Tables[0];
// What goes here?
}
我需要使用 IEnumerable 方法
如何返回包含所有只有地址的學生的 DataRows 枚舉?
我不知道你的學生 class 長什么樣,但這是一個樣機
private IEnumerable<Student> GetAddress()
{
DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students Where NOT NULL [address]"));
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
yield return new Student
{
StudentName = row["StudentName "].ToString(),
Address= row["Address"].ToString()
};
}
}
這應該讓您了解 go 從這里到哪里。
我想你在看的是
DataRow[] dr = ds.Tables[0].Select("Address NOT NULL"); // you want filtering on address column
foreach (DataRow row in dr)
{
}
IEnumerable
只是一些您可以迭代的抽象列表 - 有很多方法可以返回IEnumerable
的實例,例如:
yield return
構造(僅限 .Net 4.0)List<T>
或數組或任何其他已經實現IEnumerable
的 class ,例如:
public IEnumerable GetAddress()
{
DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students"));
DataTable dt = ds.Tables[0];
// The chances are that instead of string you will need a struct or a class
List<string> retVal = new List<string>();
foreach (DataRow row in dt)
{
// This will obviously depend on the table and return type
retVal.Add((string)row["mycol"]);
}
}
此外,根據返回的類型,您可能希望返回IEnumerable<T>
,因為它是線程安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.