Search code examples
c#ienumerable

Accessing Properties of items contained in an IEnumerable


Sorry if the title is misleading, you can correct if you have an idea what I'm trying to say.

I have a function which takes in an IEnumerable. The IEnumerable is an anonymous type.

This is my function:

public void AddToCollection_Short(IEnumerable query)
{
    List<object> list = new List<object>();

    foreach (var item in query)
    {
        var obj = new object();
        var date = item.Date.ToShortDateString();
        obj = new { date, item.Id, item.Subject };
        list.Add(obj);
    }

    AllQueries = list;
    OnPropertyChanged("AllQueries");
}

It doesn't recognize the suffix such as .Id, .Date, .Subject. May I ask what approach I should take to fix this. Is there something like IEnumerable<Datetime Date, int Id, string Subject> query?


Solution

  • You could use (in C# 4.0 and higher) the dynamic keyword or update the signature to AddToCollection_Short.

    public void AddToCollection_Short(IEnumerable query)
    {
        List<object> list = new List<object>();
        foreach (dynamic item in query)
        {
            var obj = new object();
            var date = item.Date.ToShortDateString();
            obj = new { date, item.Id, item.Subject };
            list.Add(obj);
        }
        AllQueries = list;
        OnPropertyChanged("AllQueries");
    }