Sarr Sarr - 1 year ago 41
C# Question

How to remove from Generic List an item based on class with constructor?

Searched a lot, but I can't figure this out.
I have a class armor with a few properties. I am able to add it, and I'm doing it via function which also adds sorting.

I have class Item:

public class Item : IComparable<Item>
public string name, description;
public bool stackable;
public int value;
public string coin_type;
public int weight;
// public string model_path;

public Item (string c_name, string c_description, bool c_stackable, int c_value, string c_coin_type, int c_weight)
name = c_name;
description = c_description;
stackable = c_stackable;
value = c_value;
coin_type = c_coin_type;
weight = c_weight;
// model_path = c_model_path;
//, string c_model_path)
public int CompareTo(Item other)
return String.Compare (name,; // a < ab < b (sortowanie wg. litery)

Then I have a "child" class which derives from class Item.

public class Armor : Item, IComparable <Armor>
public string armor_prof;
public string armor_category;
public int armor_class;
public int armor_str_req;
public string armor_stealth_mod;
//public string armor_property;
public Armor (string c_name, string c_description, bool c_stackable, int c_value, string c_coin_type, int c_weight, string c_armor_prof, string c_armor_category, int c_armor_class, int c_armor_str_req, string c_armor_stealth_mod) : base (c_name, c_description, c_stackable, c_value, c_coin_type, c_weight)
armor_prof = c_armor_prof;
armor_category = c_armor_category;
armor_class = c_armor_class;
armor_str_req = c_armor_str_req;
armor_stealth_mod = c_armor_stealth_mod;
// armor_property = c_armor_property;

This is the function that adds items and sorts them:

public void AddToCharacterInventory(Item it)
if (it is Weapon)
else if (it is Armor)

Then I add item:

AddToCharacterInventory(new Armor("Leather armor", "Description.", false, 10, "gp", 10, "Leather", "Light Armor", 11, 0, ""));

It's being added to list named charInvArmor. Now, how to remove it based on some property?
For example, by name "Leather Armor". So, it's public string name, which class armor inherits from class item.
It's easy to .Remove position from the list if it's a simple string, but how to do it in such case, when type is a class with properties?

Answer Source

Consider following example, it should guide you to right direction :)

static void Main()
    var items = new List<Item>()
        new Item("Axe", true),
        new Item("Armor", false),
        new Item("Horse", false)

    var remove = items.FirstOrDefault(item =>
        return item.Name.Equals("Armor", StringComparison.InvariantCultureIgnoreCase) &&

    if (remove != null)

    Console.WriteLine(string.Join(", ", items.Select(item => item.Name)));

public class Item
    public Item(string name, bool active)
        Name = name;
        Active = active;

    public string Name { get; set; }

    public bool Active { get; set; }