C#: Return IEnumerable when field is not null?

最后都变了- 提交于 2019-12-23 03:57:26

问题


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

I need to use IEnumerable methods

How can i return enumeration of DataRows containing all students that have addresses only?


回答1:


I think what you are looking is

DataRow[] dr = ds.Tables[0].Select("Address NOT NULL"); // you want filtering on address column
    foreach (DataRow row in dr)
    {

    }



回答2:


I don't know what your student class looks like but here is a mockup

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

        }

This should give you some idea of where to go from here.




回答3:


An IEnumerable is just some abstract list which you can iterate through - there are many ways of returning an instance of IEnumerable, for example:

  • Using the yield return construct (.Net 4.0 only)
  • Returning a List<T>, or array or any other class that already implements IEnumerable,

For example:

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"]);
    }
}

Also, depending on the type returned you probably want to return an IEnumerable<T> instead, as it is thread safe.



来源:https://stackoverflow.com/questions/5877600/c-return-ienumerable-when-field-is-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!