Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast C#'s linq WHERE statement?

Tags:

c#

linq

I have a class Literal and a Tag is inheriting from it.

I would like to do the following but I am getting

Unable to cast object of type 'WhereListIterator`1[Core.Literal]' to type 'System.Collections.Generic.List`1[Core.Tag]'.

 private List<Literal> literals;
public List<Tag> Tags
        {
            get { return (List<Tag>)literals.Where(x => x is Tag); }
        }

thanks

like image 626
Himberjack Avatar asked Mar 25 '11 13:03

Himberjack


1 Answers

You would be better off doing:

literals.OfType<Tag>().ToList();

This gives you a List<Tag>.

You can also do:

var asList = new List<Tag>(literals.OfType<Tag>());

Casting simply does not work because LINQ works in terms of either IEnumerable<T> or IQueryable<T> which neither use List as a backing implementation for the results. The second method I posted uses a constructor overload of List<T> the takes in an IEnumerable<T> as its initial collection of objects. Also in this scenario the OfType<T> method from LINQ is a much cleaner, shorter form of essentially filtering a list with Where(x -> x is T).

Also, OfType<T> in this scenario is a much better idea, because the result is an IEnumerable<T> of your target type. Where(x => x is T) will return an IEnumerable<T> of the original source's type. So that's why (List<Tag>)literals.Where(x => x is Tag).ToList() emit an error for invalid casts.

More information on ToList

More information on OfType

like image 129
Joshua Rodgers Avatar answered Sep 22 '22 06:09

Joshua Rodgers