Question Turning a List of Objects into a List of other Objects that inherit from a Class

playtime

New member
Joined
Apr 21, 2021
Messages
2
Programming Experience
Beginner
Hi! Been trying to learn C# for a month now, new to programming in general.
Right now, on this project, I have a List<Item> called Inventory. I want to filter every item in this list that inherits from the class Weapon into a new list called weaponlist.
The first thing I tried was
C#:
var weaponslist = Inventory.Where( x => x is Weapon).ToList();
That does seem to work, however, I want to take a Weapon from this List that now only contains Weapons and assign it to the RightHand property of my Player class, which has to be a Weapon, but of course, my weaponlist is a List<Item> and not a List<Weapon>.

So, how do I turn my List<Iitem> into a List<Weapon> once it only contains Weapons?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,387
Location
Chesapeake, VA
Programming Experience
10+

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,197
Location
Norway
Programming Experience
10+
Instead of Where you can use the OfType filter extension: Inventory.OfType<Weapon>()
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,387
Location
Chesapeake, VA
Programming Experience
10+
Top Bottom