c#:当字段不为空时返回IEnumerable

本文关键字:返回 IEnumerable 字段 | 更新日期: 2023-09-27 17:54:27

public IEnumerable GetAddress()
{
     DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students"));
     DataTable dt = ds.Tables[0];
     // What goes here?
}

我需要使用IEnumerable方法

我如何返回包含所有学生只有地址的datarow枚举?

c#:当字段不为空时返回IEnumerable

我不知道你的学生班级是什么样子的,但这里有一个模型

    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()
                                      };
            }
        }

我想你看的是

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的类,
例如:

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>,因为它是线程安全的。

相关文章: