Get properties of empty linq statement

Is there a way of looping through the properties of the underlining result of the linq statement when the linq statement contains no elements?

I would like to create a DataTable and add the individual properties as columns, but it seems this can only be done when the linq statement contains items. Please see my current code below

private static void GetProperties<T>(IEnumerable<T> query) 
{
    DataTable dt = new DataTable();

    PropertyInfo[] queryInfo = null;

    foreach (var item in query)
    {
        if (queryInfo == null) 
        {
            queryInfo = item.GetType().GetProperties();
            foreach (var info in queryInfo)
            {
                dt.Columns.Add(info.Name);
            }
        }

        DataRow dr = dt.NewRow();

        foreach (PropertyInfo pi in queryInfo)
        {
            dr[pi.Name] = pi.GetValue(item, null) ?? DBNull.Value;
        }

        dt.Rows.Add(dr);
    }
}

Desired code, or something similar:

private static void GetProperties<T>(IEnumerable<T> query) 
{
    DataTable dt = new DataTable();

    PropertyInfo[] queryInfo = null;

    queryInfo = query.FirstOrDefault().GetType().GetProperties();

    foreach (var info in queryInfo)
    {
        dt.Columns.Add(info.Name);
    }

    foreach (var item in query)
    {
        DataRow dr = dt.NewRow();

        foreach (PropertyInfo pi in queryInfo)
        {
            dr[pi.Name] = pi.GetValue(item, null) ?? DBNull.Value;
        }

        dt.Rows.Add(dr);
    }
}

I would always like the DataTable to contain the columns, even if the linq statement contains no items.

I am open to any suggestions.

Thanks.

Jon Skeet
people
quotationmark

I suspect all you're looking for it:

PropertyInfo[] queryInfo = typeof(T).GetProperties();

In other words, get the properties from the generic type argument rather than for a particular instance of that type.

people

See more on this question at Stackoverflow