Master
Master

Reputation: 2163

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?

Upvotes: 2

Views: 779

Answers (3)

Delta
Delta

Reputation: 851

You should be able to specify a type parameter to your method.

public void AddToCollection_Short<T>(IEnumerable<T> query) where T : IAmCommonInterface
{
    List<object> list = new List<object>();
    foreach (T 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");
}

and your common interface for your type paramater would have all the properties that you want on it. The advantage to this is the compiler will tell you when you try to use this on an Enumerable that doesn't have those properties.

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

If you know the type, you can cast your objects

 foreach (var item in query.Cast<YourType>())

If you don't know then you can use dynamic feature.And you can access your properties without a compile time error but if you try to access a property or a method which is not exist you will get a RuntimeBinderException in runtime.

foreach (dynamic item in query)
{
    ...
}

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190996

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");
}

Upvotes: 1

Related Questions