首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#:当字段不为空时是否返回IEnumerable?

C#:当字段不为空时是否返回IEnumerable?
EN

Stack Overflow用户
提问于 2011-05-04 09:45:40
回答 3查看 324关注 0票数 1
代码语言:javascript
复制
public IEnumerable GetAddress()
{
     DataSet ds = DataOps.GetDataSet(string.Format(" select * from Students"));
     DataTable dt = ds.Tables[0];
     // What goes here?
}

我需要使用IEnumerable方法

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-05-04 09:55:16

我想你看到的是

代码语言:javascript
复制
DataRow[] dr = ds.Tables[0].Select("Address NOT NULL"); // you want filtering on address column
    foreach (DataRow row in dr)
    {

    }
票数 1
EN

Stack Overflow用户

发布于 2011-05-04 09:53:21

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

代码语言:javascript
复制
    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()
                                      };
            }

        }

这应该会让您对下一步的方向有所了解。

票数 3
EN

Stack Overflow用户

发布于 2011-05-04 10:01:02

IEnumerable只是一些可以遍历的抽象列表--返回IEnumerable实例的方法有很多种,例如:

使用yield return构造的

  • (.Net 4.0 only)
  • Returning a List<T>,或数组或已实现IEnumerable

的任何其他类

例如:

代码语言:javascript
复制
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>,因为它是线程安全的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5877600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档