2

I am converting dataset table into custom object using linq:

  var list = (from row in ds.Tables[0].AsEnumerable()
          select new MyObj
          {
             Porp1 = row.Field<string>("field1"),
             Prop2 = row.Field<string>("field2")
          }).ToList();

How do I check that a column with specific name is exists, and if not, assign empty string?

2 Answers 2

3

something like:

 row.Columns.Contains("...") ? row.Field<string>("field1") : string.Empty

More Precisely:

 row.Table.Columns.Contains("...") ? row.Field<string>("field1") : string.Empty
0

To check if a column exists you should check if the column name exists in the DataTable.Columns colleciton like this:

// Given a datatable named table:
bool columnExists = table.Columns.Contains("columnname");

Alternatively, if you are on .Net 4, you could use the support for dynamic types to return the value of a column if a column exists and a default value in any other case. I blogged about something like that a while ago:

http://blog.rag.no/post/Update-The-DataTable-meets-dynamic-improved.aspx
and
http://blog.rag.no/post/Creating-a-monster-The-DataTable-meets-dynamic.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.