Leo
Leo

Reputation: 19

Getting properties of IEnumerable<T> (where T is object)

I have the following function:

public IEnumerable<string> PropertiesFromType<T>(IEnumerable<T> input)

From the type (T), I would like to get the names of the properties.

I have tried the following:

var properties = typeof(T).GetProperties();
//var properties = input.GetType().GetGenericArguments()[0].GetProperties(); // Doesn't work either
foreach (var item in properties)
{
    Console.WriteLine(item.Name);
}

// By input it does work
var inputProperties = input.First().GetType().GetProperties();
foreach (var item in inputProperties)
{
    Console.WriteLine(item.Name);
}

When sending an anonymous IEnumerable<object> into the function, it has no properties when retrieving the Type from T.

However, when using the Type of an item in the IEnumerable, it does have properties.

As suggested by: How to get the type of T from a member of a generic class or method? using the GetGenericArguments function neither returns properties.

Example: https://dotnetfiddle.net/Widget/uKzO6H

Edit: I guess what I was trying to say: Is it possible to get the Type of anonymous objects in an IEnumerable without having an instance of, by using the T.

I now realize that is impossible, as T will always be object for anonymous objects.

Upvotes: 1

Views: 2020

Answers (1)

VDWWD
VDWWD

Reputation: 35524

I'm not sure this is what you want, but the method below takes the first element of the list and returns it's properties.

public IEnumerable<string> PropertiesFromType<T>(IEnumerable<T> input)
{
    var item = input.First();
    var properties = new List<string>();

    foreach (PropertyInfo property in item.GetType().GetProperties())
    {
        properties.Add(property.Name);
    }

    return properties;
}

Usage example

public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime PublishDate { get; set; }
}

var PropertyList = PropertiesFromType<Book>(MyListOfBooks);

Upvotes: 2

Related Questions