如何在观察空值时将DataTable转换为List <t> </t>

时间:2013-12-23 09:36:47

标签: c# list datatable dbnull

电影课

public class Movie
{
    #region Properties
    public string Name { get { return _name; } set { _name = value; } }
    public string Producer { get { return _producer; } set { _producer = value; } }
    public int Rating { get { return _rating; } }
    public Image Covor { get; set; }
    public string Description { get { return _description; } }
    public int ReleaseYear { get { return _releaseYear; } set { _releaseYear = value; }}
    #endregion

    #region Private Fields
    private string _name;
    private string _producer;
    private int _rating;
    private string _description;
    private int _releaseYear;
    #endregion

    #region Constructors
    public Movie()
    {
    }

    public Movie(string name, int yearRelease)
    {
        this._name = name;
        this._releaseYear = yearRelease;
    }

    public Movie(string name, int yearRelease, string producer)
    {
        this._name = name;
        this._releaseYear = yearRelease;
        this._producer = producer;
    }
    #endregion
}   

我的尝试

foreach (DataRow movieRow in MovieTable().AsEnumerable())
{
    if (movieRow["Producer"] != DBNull.Value)
    {
        Movie movie = new Movie()
        {
            Name = (string)movieRow["Name"],
            Producer = (string)movieRow["Producer"],
            ReleaseYear = (int)movieRow["Release Year"]
        };
        movieList.Add(movie);
    }
    else
    {
        Movie movie = new Movie()
        {
            Name = (string)movieRow["Name"],
            ReleaseYear = (int)movieRow["Release Year"]
        };
        movieList.Add(movie);
    }
}

这是我的代码到目前为止我正在尝试将表转换为List。唯一的问题是DBNull的。

我想将整个表更新为列表,这当前适用于2种情况,但我需要List包含所有信息(如果存在)。我可以创建elseif语句来处理每个可能的场景,但必须有一种更好的方法来确定类型是否为DBNull,如果没有正确设置属性。

如果有任何困惑告诉我它是什么,我会进一步解释。

2 个答案:

答案 0 :(得分:0)

一个选项:您可以查看IsNull(column)

    Movie movie = new Movie()
    {
        Name = movieRow.IsNull("Name") 
               ? (string)null : (string)movieRow["Name"],
        Producer = movieRow.IsNull("Producer") 
               ? (string)null : (string)movieRow["Producer"],
        // etc..
    };
    movieList.Add(movie);

答案 1 :(得分:0)

一种选择是使用速记代码将null-check合并到set-statements中,只需使用简写代码:

Name = (movieRow["Name"] == DBNull.Value) ? 
              (string)movieRow["Name"] : 
              string.Empty,

// Producer will be given a value if it exists, or null otherwise:
Producer = (movieRow["Producer"] == DBNull.Value) ? 
              (string) movieRow["Producer"] : 
              null,
...

如果更适合您,您可以将string.Empty替换为null,反之亦然。


编辑:这是一个非常基本的说明,因为您声明自己不熟悉编程:此简写表示“如果firstValue为真,则返回secondValue否则,返回thirdValue

var result = firstValue ? secondValue : thirdValue;