c# - 从 DataTable 获取单个值的最佳方法?

标签 c# .net datatable data-access

我有许多静态类包含这样的表:

using System;
using System.Data;
using System.Globalization;

public static class TableFoo
{
    private static readonly DataTable ItemTable;

    static TableFoo()
    {
        ItemTable = new DataTable("TableFoo") { Locale = CultureInfo.InvariantCulture };
        ItemTable.Columns.Add("Id", typeof(int));
        ItemTable.Columns["Id"].Unique = true;
        ItemTable.Columns.Add("Description", typeof(string));
        ItemTable.Columns.Add("Data1", typeof(int));
        ItemTable.Columns.Add("Data2", typeof(double));

        ItemTable.Rows.Add(0, "Item 1", 1, 1.0);
        ItemTable.Rows.Add(1, "Item 2", 1, 1.0);
        ItemTable.Rows.Add(2, "Item 3", 2, 0.75);
        ItemTable.Rows.Add(3, "Item 4", 4, 0.25);
        ItemTable.Rows.Add(4, "Item 5", 1, 1.0);
    }

    public static DataTable GetItemTable()
    {
        return ItemTable;
    }

    public static int Data1(int id)
    {
        DataRow[] dr = ItemTable.Select("Id = " + id);
        if (dr.Length == 0)
        {
            throw new ArgumentOutOfRangeException("id", "Out of range.");
        }

        return (int)dr[0]["Data1"];
    }

    public static double Data2(int id)
    {
        DataRow[] dr = ItemTable.Select("Id = " + id);
        if (dr.Length == 0)
        {
            throw new ArgumentOutOfRangeException("id", "Out of range.");
        }

        return (double)dr[0]["Data2"];
    }
}

有没有更好的方法来编写 Data1 或 Data2 方法,从与给定 ID 匹配的单个行返回单个值?

更新#1:

我创建了一个看起来相当不错的扩展方法:

public static T FirstValue<T>(this DataTable datatable, int id, string fieldName)
{
    try
    {
        return datatable.Rows.OfType<DataRow>().Where(row => (int)row["Id"] == id).Select(row => (T)row[fieldName]).First();
    }
    catch
    {
        throw new ArgumentOutOfRangeException("id", "Out of range.");
    }
}

然后我的 Data1 方法变为:

public static int Data1(int id)
{
    return ItemTable.FirstValue<int>(id, "Data1");
}

Data2 变成:

public static double Data2(int id)
{
    return ItemTable.FirstValue<double>(id, "Data2");
}

感谢您的所有回复,尤其感谢 Anthony Pegram,他提供了非常好的单行 LINQ 和 Lambda 代码。

最佳答案

您是否考虑过使用 Linq (to DataSets) ?使用 Linq 表达式,您根本不需要那些 Data1 和 Data2 函数,因为查找和过滤可以在一行代码中进行。

示例添加:

在这里从臀部射击,所以请对它持保留态度(不要靠近 IDE:)

DataTable itemTbl = GetItemTable().AsEnumerable();

double dt1 = ((From t In itemTbl Where t.Id = <your_id> Select t).First())["Data1"];

那是两行代码,但您可以轻松地包装 Enumerable 的获取。

关于c# - 从 DataTable 获取单个值的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2637417/

相关文章:

r - 将分页放在 R 中 DT 数据表的顶部?

javascript - 如何在数据表中显示 5 行而不是默认的 10 行?

c# - .net 标准库中的 HttpContext

c# - 在 C# 中返回 'this' 的数组

c# - 使用安全枚举在 C# 4.0 中线程安全地替换 ObservableCollection<T>

c# - 尝试从数据库填充 DropDownListFor 时出错

asp.net - 带有自定义 slugs 的 .NET MVC-4 路由

c# - 在字典中存储委托(delegate)

.NET:从 LINQ to SQL 到 Entity Framework 的转换

javascript - 转换数据表列日期格式