E
E
Evgeny Shinkarev2020-04-13 15:38:55
C++ / C#
Evgeny Shinkarev, 2020-04-13 15:38:55

How to change the values ​​of an object from a list if the list contains it?

There is a list of objects.

class Program
{
    List<Item> items = new List<Item>;
    items.Add(new Item(){ItemName = "Ball", ItemID = 10, ItemCost = 3})
    items.Add(new Item(){ItemName = "Toy", ItemID = 14, ItemCost = 15})
}

Object class:
public class Item
{
    public string ItemName { get; set;}
    public int ItemID { get; set; }
    public double ItemCost { get; set;}
}


It is required to check for the presence of an object with the specified string in this list (search by name), and, if this element is present, change its ItemID and ItemCost.
How can I implement this?
Thank you very much!

ps: The example here is very primitive. In reality, the ItemID and ItemCost values ​​will change very often, and the list itself will contain a huge number of objects.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
edward_freedom, 2020-04-13
@Shinkero

public class Item
        {
            public Item(string name, int id, double cost)
            {
                Name = name;
                Id = id;
                Cost = cost;
            }

            public string Name { get; set; }
            public int Id { get; set; }
            public double Cost { get; set; }

            public override string ToString()
            {
                return $"Id: {Id}, Name: {Name}, Cost: {Cost}";
            }
        }

        static void Main(string[] args)
        {
            var findName = "Ball";

            var items = new List<Item>
            {
                new Item("Ball", 10, 3),
                new Item("Toy", 14, 15)
            };

            var item = items.FirstOrDefault(product => product.Name.Contains(findName));

            if (item != null)
            {
                item.Cost = 100;
                item.Id = 999;
            }

            Console.WriteLine(string.Join(Environment.NewLine, items));

            Console.ReadKey();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question