簡體   English   中英

C#:當字段不是 null 時返回 IEnumerable?

[英]C#: Return IEnumerable when field is not null?

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

我需要使用 IEnumerable 方法

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

我不知道你的學生 class 長什么樣,但這是一個樣機

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

        }

這應該讓您了解 go 從這里到哪里。

我想你在看的是

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的 class ,

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM