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.
Foo foo = dt.AsEnumerable().Select(dr =>
new Foo { Bar = Convert.ToIn32(dr["Bar"]),
Baz = Convert.ToDecimal(dr["Baz"]) }).Single();