Malcolm
Malcolm

Reputation: 12874

How do I convert a non-Generic IList to IList<T>?

I have class that wants an IList<T>, but I have a Systems.Collection.IList, coming from an NHibernate quere.

I want to create a method that converts it to an IList<T>. How do I do this?

Upvotes: 49

Views: 36449

Answers (7)

nnunes10
nnunes10

Reputation: 550

No need for use Linq in this case (OfType() or .Cast). NHibernate implementation is enough.

You just have to use:

var results= query.List<YourType>();

Instead of

var results= query.List<>();

Upvotes: -2

Ram Karri
Ram Karri

Reputation: 41

Fredrick is correct. But Nhibernate also has an option to return multiple result sets. For example:

  IList multiResults = session.CreateMultiCriteria()
                .Add(pageCriteria)
                .Add(countCriteria)
                .List();

In the above call there isn't an option to return a typed list. So it has to be casted as mentioned above, like this:

 IList<T> results = ((IList)multiResults[0]).Cast<T>().ToList();
            IList counts = (IList)multiResults[1];

Upvotes: 4

mako
mako

Reputation: 43

Frederik is correct, NHibernate already does this.

var data = query.List<MyType>();

This would result in an IList of the type you specified. In this case IList<MyType>.

Upvotes: 1

Scott Wisniewski
Scott Wisniewski

Reputation: 25061

Cast and OfType return IEnumerable<T> implemetnations, not IList<T> implementations, so they wouldn't be useful to you.

Calling .Cast<T>().ToList will result in an extra copy of the list, which may have adverse performance implications.

A better (IMHO) approach would be to just create a wrapper class and do the conversion on the fly. You want something like this:

class ListWrapper<T> : IList<T>
{
    private IList m_wrapped;

    //implement all the IList<T> methods ontop of m_wrapped, doing casts
    //or throwing not supported exceptions where appropriate.
    //You can implement 'GetEnumerator()' using iterators. See the docs for 
    //yield return for details
}

That will have the advantage of not create another copy of the entire list.

Upvotes: 6

Miha Markic
Miha Markic

Reputation: 3250

One way is to use Linq, like list.OfType<T>() or .Cast<T>()

Upvotes: 5

Tamas Czinege
Tamas Czinege

Reputation: 121424

If you're sure that all of the elements inherit from T (or whatever type you're using)

IList<T> myList = nonGenericList.Cast<T>().ToList();

If you're not sure:

IList<T> myList = nonGenericList.OfType<T>().ToList();

Of course, you will need the System.Linq namespace:

using System.Linq;

Upvotes: 85

Frederik Gheysels
Frederik Gheysels

Reputation: 56964

Can't you achieve that NHibernate returns you an IList ? The ICriteria interface defines an List<T> method ...

Upvotes: 1

Related Questions