Is there a way to store a reference from lambda " .Exists" ?

This is my method of Adding into storage

    private List<Item> itemsInStorage = new List<Item> ();
   

    public void AddItemsToStorage(Item item)
    {

        if (itemsInStorage.Exists (x => x.ID == item.ID)) {
            Debug.Log ("Item Exist Adding To Appropriate Count");
            for (int i = 0; i < itemsInStorage.Count; i++) {
                if (itemsInStorage [i].ID == item.ID) {
                    itemsInStorage [i].Count += item.Count;
                }
            }
        } else
        {
            Debug.Log ("Item Does Not Exist Adding Item");
            itemsInStorage.Add (item);
        }
    }

but i kinda know of the thing i am looking for from the lambda, then there would be no need to do a loop to find that thing again… : - )

How about using Find instead? It returns the first element that matches a predicate or null if it doesn’t find one.

1 Like

Yes That’s What i Was Looking For, Thanks : - )

You are welcome!

As an additional information, in a higher C# version you don’t even have to explicitely perform a null-check anymore, if working with nullable types. This works fine:

        List<GameObject> list = new List<GameObject>() { /* some GameObjects */ };
        GameObject obj;
        if(obj = list.Find(item => item.name == "someName")){
            // do something with obj
        }