C#:当字段不为空时返回IEnumerable?
public IEnumerable GetAddress() { DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students")); DataTable dt = ds.Tables[0]; // What goes here? }
我需要使用IEnumerable方法
如何返回包含仅具有地址的所有学生的DataRows枚举?
我想你在想什么
DataRow[] dr = ds.Tables[0].Select("Address NOT NULL"); // you want filtering on address column foreach (DataRow row in dr) { }
我不知道你的学生class级是什么样的,但这里是一个样机
private IEnumerable 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() }; } }
这应该会让你知道从这里去哪里。
IEnumerable
只是一些可以迭代的抽象列表 – 有许多方法可以返回IEnumerable
的实例,例如:
- 使用
yield return
构造(仅限.Net 4.0) - 返回
List
,或者已经实现IEnumerable
数组或任何其他类,
例如:
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 retVal = new List (); foreach (DataRow row in dt) { // This will obviously depend on the table and return type retVal.Add((string)row["mycol"]); } }
此外,根据返回的类型,您可能希望返回IEnumerable
,因为它是线程安全的。