check if list contains item with matching string property

im making an inventory of items, i have an items class with each item instance having a name and quantity, i want to add items to the list if the check returns with “nothing found.” If i find something and the quantity is 1 or more, i want to increase that items quantity instead of adding a new object.

Im using C#

public void AddItem(string name, int price, string type, int value, string info, int quantity, bool equipped){
		for(int I = 0; I < items.Count; I++){
			if(items*.itemName == name){*

_ items*.quantity += quantity;_
_
}_
_
else{_
_
Item ni = new Item();_
_
ni.itemName = name;_
_
ni.price = price;_
_
ni.type = type;_
_
ni.value = value;_
_
ni.info = info;_
_
ni.quantity = quantity;_
_
ni.equipped = equipped;_
_
items.Add (ni);*_

* }*
* }*
* }*

Using Linq this is pretty easy. You would have to add using System.Linq;

public void AddItem(string iname, int price, string type, int value, string info, int quantity, bool equipped){

    Item foundItem = items.FirstOrDefault(i => i.itemName == iname);
    if (foundItem != null)
    {
        Item ni = new Item();
        ni.itemName = name;
        ni.price = price;
        ni.type = type;
        ni.value = value;
        ni.info = info;
        ni.quantity = quantity;
        ni.equipped = equipped;
        items.Add(ni);
    }
    else
        foundItem.quantity++;
}

This way it will look for the first item in the list with that name. If there is no item with that name, it will create a new one and add it to the list, if the item is found it will increase its quantity.

Ah, I actually didn’t notice that. What you’re doing now is going through the items in “items”, and for every item, if it is not the same as the item you’re trying to add, it will add it. So if you have a list of 10 items and try to add an item that is not in the list, you will add the item 10 times.

You could do something like this:

public void AddItem(string name, int price, string type, int value, string info, int quantity, bool equipped){

			bool isInList = false;

			for(int I = 0; I < items.Count; I++){
				if(items*.itemName == name){*

_ items*.quantity += quantity;_
_
isInList = true;_
_
}_
_
}*_

* // Outside for loop*
* if (isInList == false){*
* Item ni = new Item();*
* ni.itemName = name;*
* ni.price = price;*
* ni.type = type;*
* ni.value = value;*
* ni.info = info;*
* ni.quantity = quantity;*
* ni.equipped = equipped;*
* items.Add (ni);*
* }*
* }*
Noticed you’re using a list, and ofc items.Count is fine