简体   繁体   English

如何在数据表列中获取不为空的值

[英]How to get a value that is not null in a datatable column

I have a datatable and I want to get the values that is not null or empty in one column. 我有一个数据表,我想在一列中获取不为null或为空的值。

This is my datatable (dt) 这是我的数据表(dt)

emp_id     emp_name      gender       Position
1          Peter         M            Trainee
2          Amy           F            
3          Jessica       F
4          Josh          M            Clark
5          Tony          M            Manager



  DataTable dt = new DataTable();

   dt.Columns.Add("emp_name", typeof(string));
   dt.Columns.Add("gender", typeof(string));
   dt.Columns.Add("Position", typeof(string));


   foreach(DataRow row in dt.Rows){
        //get the values in position column that is not null (This does not work)
        string position = row.Field<string>(2);

   }

In this table, you can see Amy and Jessica's position is empty. 在此表中,您可以看到Amy和Jessica的职位为空。 When I am looping through this table, how can I get the string value that is not null in the position column? 当我遍历此表时,如何获得位置列中不为null的字符串值? Help will be appreciated. 帮助将不胜感激。 Thanks 谢谢

Try this 尝试这个

  DataTable dt = new DataTable();

  dt.Columns.Add("emp_name", typeof(string));
  dt.Columns.Add("gender", typeof(string));
  dt.Columns.Add("Position", typeof(string));

  DataRow[] result = dt.Select("Position != null and Position != ''");
  foreach (DataRow row in result)
  {
      string position = row.Field<string>(2);
  }

Try this - 尝试这个 -

        foreach (DataRow row in dt.Rows)
        {
            //get the values in position column that is not null (This does not work)
            var position = row.Field<string>("Position");

            if (string.IsNullOrEmpty(position))
            {
                //Null or empty
            }
            else
            {
                //Not null
            }

        }

Maybe This code help you: 也许这段代码可以帮助您:

public static T GetReaderValue<T>(SqlDataReader reader, string fieldName)
        {
            if (reader != null && reader[fieldName] != null)
            {
                object value = reader[fieldName];
                if (value is DBNull)
                    return default(T);
                return (T)reader[fieldName];
            }
            return default(T);
        }

using: 使用:

result.OfficeID = GlobalUtilities.GetReaderValue<int>(reader, "OfficeID");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM