Unable to cast to object

51 Views Asked by At

I had a code:

var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
var list = new List<IBO>(result.OfType<IBO>());

But I need to be able to add many elements in a list. I tried:

var list = new List<IBO>();
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
list.Add((IBO)result.OfType<IBO>());

Which results in an error:

Unable to cast object of type '<OfTypeIterator>d__95`1[BO.IBO]' to type 'BO.IBO'.

How to resolve this?

3

There are 3 best solutions below

0
Mong Zhu On BEST ANSWER

OfType will return a collection: IEnumerable. The problem is that you try to cast this entire collection to a single element. Hence the error message.

The cast is already performed by the OfType call. You would need a different adding method. It is called AddRange.

Adds the elements of the specified collection to the end of the List.

list.AddRange(result.OfType<IBO>());
0
Guru Stron On

The second snippet should use AddRange without extra casting to IBO:

Adds the elements of the specified collection to the end of the List<T>.

var list = new List<IBO>();
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
list.AddRange(result.OfType<IBO>());

Note that both snippets will doe the same. If you have only one source collection then just use the first one.

0
MakePeaceGreatAgain On

You don't need an extra Add***-call, just use the constructor that expects an IEnumerable<IBO>:

var list = new List<IBO>(result.OfType<IBO>());

But I need to be able to add many elements in a list.

In fact the above does exactly that: it adds all the elements of the specified type into your newly created list.

Alternativly use this:

var list = result.OfType<IBO>().ToList();