Object initialization from single DataRow
-
26-10-2019 - |
Question
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.
Solution
Foo foo = dt.AsEnumerable().Select(dr =>
new Foo { Bar = Convert.ToIn32(dr["Bar"]),
Baz = Convert.ToDecimal(dr["Baz"]) }).Single();
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow