Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast/Convert IEnumerable<T> to IEnumerable<U>?

The following complies but at run time throws an exception. What I am trying to do is to cast a class PersonWithAge to a class of Person. How do I do this and what is the work around?

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class PersonWithAge
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<PersonWithAge> pwa = new List<PersonWithAge>
        {
            new PersonWithAge {Id = 1, Name = "name1", Age = 23},
            new PersonWithAge {Id = 2, Name = "name2", Age = 32}
        };

        IEnumerable<Person> p = pwa.Cast<Person>();

        foreach (var i in p)
        {
            Console.WriteLine(i.Name);
        }
    }
}

EDIT: By the way PersonWithAge will always contain the same properties as Person plus a couple more.

EDIT 2 Sorry guys but I should have made this a bit clearer, say I have two db views in a database that contains the same columns but view 2 contains 1 extra field. My model view entities are generated by a tool that mimics the database views. I have a MVC partial view that inherits from one of the class entities but I have more than one way to grab data...

Not sure if this helps but it means that I cant make personWithAge inherit from person.

like image 477
Rippo Avatar asked Nov 21 '09 16:11

Rippo


People also ask

What is t in IEnumerable?

IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.

Can you cast IEnumerable to list?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

What is IEnumerable<> in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

Why we use IEnumerable in C#?

IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.


1 Answers

You can't just cast two unrelated type into each other. You could make it possible to convert PersonWithAge to Person by letting PersonWithAge inherit from Person. Since PersonWithAge is obviously a special case of a Person, this makes plenty of sense:

class Person
{
        public int Id { get; set; }
        public string Name { get; set; }
}

class PersonWithAge : Person
{
        // Id and Name are inherited from Person

        public int Age { get; set; }
}

Now if you have an IEnumerable<PersonWithAge> named personsWithAge, then personsWithAge.Cast<Person>() will work.

In VS 2010 you will even be able to skip the cast altogether and do (IEnumerable<Person>)personsWithAge, since IEnumerable<T> is covariant in .NET 4.

like image 156
Joren Avatar answered Oct 09 '22 11:10

Joren