I have a simple datatable like this:
F1 F2
A 1
B 2
I want to return the value of F2 where F1 is a certain value. This code works when the row exists:
DataTable dt = null;
DataRow dr = null;
string strTemp = null;
//define datatable
dt = new DataTable();
dt.Columns.Add("F1");
dt.Columns.Add("F2");
//add 2 rows
dr = dt.NewRow();
dr["F1"] = "1";
dr["F2"] = "A";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["F1"] = "2";
dr["F2"] = "B";
dt.Rows.Add(dr);
//this returns "A"
strTemp =
dt.AsEnumerable().
Where(x => x.Field<string>("F1") == "1").
FirstOrDefault().Field<string>("F2");
But I get a value cannot be null error when I try to search for a value that does not exist:
strTemp =
dt.AsEnumerable().
Where(x => x.Field<string>("F1") == "123"). //this gets an error because 123 does not exist
FirstOrDefault().Field<string>("F2");
How can I handle this? (Also is this best practice for doing the search?)