public IEnumerable GetAddress()
{
DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students"));
DataTable dt = ds.Tables[0];
// What goes here?
}我需要使用IEnumerable方法
如何返回包含所有只有地址的学生的DataRows枚举?
发布于 2011-05-04 09:55:16
我想你看到的是
DataRow[] dr = ds.Tables[0].Select("Address NOT NULL"); // you want filtering on address column
foreach (DataRow row in dr)
{
}发布于 2011-05-04 09:53:21
我不知道你的学生类是什么样子的,但这里有一个模型
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()
};
}
}这应该会让您对下一步的方向有所了解。
发布于 2011-05-04 10:01:02
IEnumerable只是一些可以遍历的抽象列表--返回IEnumerable实例的方法有很多种,例如:
使用yield return构造的
List<T>,或数组或已实现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<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>,因为它是线程安全的。
https://stackoverflow.com/questions/5877600
复制相似问题