B. Nir
B. Nir

Reputation: 119

getting specific x items from list using linq

I am trying to get specific x items from a list I created.

List<Item> il = (List<Item>)(from i in AllItems
                             where i.Iid == item.Iid
                             select i).Take(Int32.Parse(item.amount));

I get the following error:

"Unable to cast object of type 'd__3a`1[AssetManagement.Entities.Item]' to type 'System.Collections.Generic.List`1[AssetManagement.Entities.Item]'."

How can it be fixed and why is this happening?

Upvotes: 0

Views: 3662

Answers (3)

EZI
EZI

Reputation: 15354

Isn't this syntax more readable? (The only difference from your query is the ToList())

List<Item> il = AllItems.Where(i => i.Iid == item.Iid)
                        .Take(Int32.Parse(item.amount))
                        .ToList();

I never liked using parentheses to materialize the query (from..where..select).ToList();

Upvotes: 3

King King
King King

Reputation: 63317

List<Item> il = (from i in AllItems
                 where i.Iid == item.Iid
                 select i).Take(Int32.Parse(item.amount)).ToList();

NOTE: Casting can be done only between objects with the Inheritance or Implementation relationship. Try to remember that.

Upvotes: 3

wexman
wexman

Reputation: 1295

You're missing the ".ToList()" call at the end as KingKing correctly pointed out. Without that, that query will result in an IQueryable that cannot be cast to List.

As a side node, I'd prefer using implicit variable type declaration, like

var il = (from i in AllItems
    where i.Iid == item.Iid
    select i).Take(Int32.Parse(item.amount)).ToList();

This way, it wouldn't have thrown an exception even without the "ToList" (but maybe it wouldn't have been what you expected)

Upvotes: 5

Related Questions