开发者

C#: Return IEnumerable when field is not null?

public IEnumerable GetAddress()
{
     DataSet ds = DataOps.GetDat开发者_运维知识库aSet(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?


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.


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)
    {

    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜