-1

To populate a List from a DataTable I typically write a statement like this:

List<Foo> foos = dt.AsEnumerable().Select(dr =>
    new Foo { Bar = Convert.ToIn32(dr["Bar"]),
              Baz = Convert.ToDecimal(dr["Baz"]) }).ToList();

How may I write a similar statement to initialize a single object when I know the DataTable will return just 1 row like the following pseudo code:

Foo foo = dt.Rows[0].Select(dr =>
    new Foo { Bar = Convert.ToIn32(dr["Bar"]),
              Baz = Convert.ToDecimal(dr["Baz"]) });

I would like to write just one statement and want to avoid (if possible) 2 lines like this:

DataRow dr = dt.Rows[0];
Foo foo = new Foo { Bar = Convert.ToIn32(dr["Bar"]),
                    Baz = Convert.ToDecimal(dr["Baz"]) });

I have tried combinations of Where, Select, First, Single but cannot hit the nail on the head!

Any answers as ever are appreciated.

Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
  • Out of curiosity, what is the origin of the DataRow here? there may be ways to skip the DataRow entirely – Marc Gravell Oct 18 '11 at 13:35
  • The origin of the DataRow is the result of a SQL Stored Proc that returns a DataTable with one row. – Barry Kaye Oct 18 '11 at 13:39
  • my point is - a stored proc doesn't *really* return a `DataTable`. That is just data-adapter etc. You can omit the `DataTable` *completely* - you *might* (up to you) want to look at `IDataReader`, or tools like "dapper-dot-net" (which will do all the mapping for you) – Marc Gravell Oct 18 '11 at 13:42

2 Answers2

2
Foo foo = dt.AsEnumerable().Select(dr =>
    new Foo { Bar = Convert.ToIn32(dr["Bar"]),
              Baz = Convert.ToDecimal(dr["Baz"]) }).Single();
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Well you can do:

Foo foo = new Foo { Bar = Convert.ToIn32(dt.Rows[0]["Bar"]),
                    Baz = Convert.ToDecimal(dt.Rows[0]["Baz"]) };

... but personally I'd prefer the version with a separate variable for the common expression.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194