HotTomales
HotTomales

Reputation: 564

Insert LINQ Query Results Into DataTable

I am using a LINQ Query to get data from linked Entity Framework Tables. How do I take the the variable I am storing the results in and create a DataTable?

In the code below, how could I create a DataTable of all the results that the variable empInfo holds?

var empInfo = (from import in db.HmspreadsheetImports
join hpp in db.Hppings on import.VText equals hpp.HAu
where import.importDT >= DateTIme.Parse(currDate)
select new Label {
    LastName = hpp.lastname,
    FirstName = hpp.firstname,
    Address1 = hpp.Address1,
    City = import.city,
    State = import.state
}).ToList();

Upvotes: 1

Views: 943

Answers (2)

Selim Yildiz
Selim Yildiz

Reputation: 5370

You can use this Extension method to convert IList to DataTable:

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable("Results");
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name,  Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
}

Then implementation just like this:

DataTable dtempInfo = empInfo.ToDataTable<Label>();

Upvotes: 1

Orace
Orace

Reputation: 8359

MoreLINQ is available via NuGet package and provide a ToDataTable extension method that:

Appends elements in the sequence as rows of a given (or new) object (DataTable) with a set of lambda expressions specifying which members (property or field) of each element in the sequence will supply the column values.

Upvotes: 0

Related Questions