Search Results

Search found 1 results on 1 pages for 'piersmyers'.

Page 1/1 | 1 

  • Best way to get a single value from a DataTable?

    - by PiersMyers
    I have a number of static classes that contain tables like this: 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"]; } } Is there a better way of writing the Data1 or Data2 methods that return a single value from a single row that matches the given id?

    Read the article

1