Search code examples
linqilist

Convert a DataTable to IList


I am updating some legacy that has a Table that only contains one row. I want to convert it to an IList. The idea is that the first property of IFoo is Name which would be the column name from the Table and the second if Value which is the value of the column.

/// <summary>
/// Name = Column Name
/// </summary>
String Name { get; set; }
/// <summary>
/// Value = Column Value
/// </summary>
String Value { get; set; }

The data may look something this

Foo1     Foo2     Foo3    Foo4     Foo5

xyz      zyx      abc     def      ghi 

And would be:

Foo1, xyz

Foo2, zyx

Foo3, abc

Foo4, def

Foo5, ghi

I am not really sure how to accomplish this. Seems like there could be a linq query to do it. Any help would be appreciated.

Rhonda


Solution

  • Perhaps (works also if the table contains more rows):

    IList<Foo> data = table.AsEnumerable()
        .SelectMany(r => table.Columns.Cast<DataColumn>()
            .Select(col => new Foo
            {
                Name = col.ColumnName,
                Value = r.IsNull(col) ? null : r[col].ToString()
            }))
        .ToList();