我有许多包含此类的静态类:
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的获取.