使用自定义类来获取她的行值的典型DataTable

时间:2015-03-18 23:24:15

标签: c# .net datatable

我一直在寻找一些方法来使用DataTables并使用自定义类获取她的行的值。

我的方法如下:

DataTable dtUsers = new DataTable();

dtUsers.Columns.Add("Name");
dtUsers.Columns.Add("Last name");
dtUsers.Columns.Add("Age", typeof(int));

for (int x = 1; x <= 100; x++)
{
    dtUsers.Rows.Add(new object[]
    {
        "Name " + x,
        "Last name " + x,
        x
    });
}

// I want to do this
var Name = dtUsers.Rows[0].Name; // Get "Name 1"
var Age = dtUsers.Rows[50].Age; // Get "Age 50"

// Or
foreach(DataRow drCurrent in dtUsers.Select("Age > 50"))
{
    int Age = drCurrent.Age; // Get 51,52,53..
}

我在想这样的事情:

public class DataTablePerson : DataTable
{
    public string Name { get; set; } // Implement a method to return a specific value in some specific row
    public string Last_name { get; set; } // Implement a method to return a specific value in some specific row
    public int Age { get; set; }// Implement a method to return a specific value in some specific row
}

是否存在实现此目的的方法?

如果我可以使用自定义类作为参数使用某些类型化的类来重新应用此类其他结构(例如:人物,树,电影,书籍),那么将会有用。

2 个答案:

答案 0 :(得分:1)

错误,不要为您的应用程序使用基于数组的数据模型。 I have blogged it why。而是将数据表转换为您自己的类模型(POCO)的List / Array / Enumerable并改为使用它。

但是如果你坚持使用它(虽然它是你自己的选择),你可以使用&#34;包装类&#34;。

public class DataTablePerson{
    public DataTablePerson(DataTable source){
        this.Source = source;
    }
    protected DataTable Source = null;

    public string Name(int row = 0){
        return Get("name", row);
    }
    public string LastName(int row = 0){
        return Get("last_name", row);
    }
    public int Age(int row = 0){
        return Convert.ToInt32(Get("age", row));
    }

    protected string Get(string name, int row){
        return source.Rows[row][name].ToString();
    }
}

并使用它:

DataTablePerson dtp = new DataTablePerson(dtUsers);
string name = dtp.Name(1);

或者如果你想要行级实体(你可以使用交换中的属性):

public class DataRowPerson{
    public DataRowPerson(DataRow source){
        this.Source = source;
    }
    protected DataRow Source = null;

    public string Name(){
        return source["name"].ToString();
    }
    public string LastName(){
        return source["last_name"].ToString();
    }
    public int Age(){
        return Convert.ToInt32(source["age"].ToString()));
    }
}

并使用它:

foreach(DataRow drCurrent in dtUsers.Select("Age > 50"))
{
    DataRowPerson drp = new DataRowPerson(drCurrent);
    int Age = drp.Age; // Get 51,52,53..
}

答案 1 :(得分:0)

你几乎拥有它!只需要代替使用属性表示法,您只需将列名指定为方括号内的字符串:

var Name = dtUsers.Rows[0]["Name"];
var Age = dtUsers.Rows[50]["Age"];

或者:

var agesOverFifty = new List<int>();
foreach (DataRow currentRow in dtUsers.Select("Age > 50"))
{
    agesOverFifty.Add(Convert.ToInt32(currentRow["Age"]));
}

甚至使用LINQ:

List<int> agesOverFifty = dtUsers.Select("Age > 50")
    .Select(row => Convert.ToInt32(row["Age"]))
    .ToList();

Console.WriteLine("The average age of a person over 50 in our sample is: {0}",
    agesOverFifty.Average());