shlomjmi
shlomjmi

Reputation: 697

Datatable to object conversion

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?

Upvotes: 2

Views: 1191

Answers (2)

Rune Grimstad
Rune Grimstad

Reputation: 36340

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

Upvotes: 0

Mor Shemesh
Mor Shemesh

Reputation: 2899

something like:

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

More Precisely:

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

Upvotes: 3

Related Questions