SharpUser
SharpUser

Reputation: 97

Contains method in 2D collection

How to compare auto[0] in cars array by "Name" field? The string if (!cars.Contains(auto[0])) is incorrect ofcourse.


namespace AutoSqare
{
    class CarsInfo
    {
        static List<Tech> cars = new List<Tech>();
        public class Tech
        {
            public string Name { get; set; }
            public double KM { get; set; }
        }
        static void Main()
        {
            string[] auto = new string[]{"Lada Vesta"};
            cars.Add(new Tech()
            {
                    Name = "Lada Vesta Sport",
                    KM = 190
            });

            if (!cars.Contains(auto[0]))
            cars.Add(new Tech()
            {
                    Name = auto[0],
                    KM = 0
            });

        }
    }
}

Upvotes: 1

Views: 47

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

You can use LINQ's Any() method:

if (!cars.Any(c => c.Name == auto[0]))

But it seems that you plan to have only unique car names, so using a Dictionary<string,Tech> seems better than a List<Tech>:

static Dictionary<string, Tech> cars = new Dictionary<string,Tech>();

static void Main()
{
    string[] auto = new string[]{"Lada Vesta"}; // <-- you also had a syntax error here
    Tech tech = new Tech()
        {
            Name = "Lada Vesta Sport",
            KM = 190
        };
    cars.Add(tech.Name, tech);        

    if (!cars.ContainsKey(auto[0]))  // <--- Use ContainsKey here
        cars.Add(auto[0], new Tech()
            {
                Name = auto[0],
                KM = 0
            });
}

Upvotes: 2

LuckyLikey
LuckyLikey

Reputation: 3840

        if (!cars.Any(car => car.Name.Equals(auto[0])))
            cars.Add(new Tech()
            {
                Name = auto[0],
                KM = 0
            });

Any will return true, if there is an element within the collection that satisfies the condition, the Condition being car.Name.Equals(auto[0]). Thats why you can use !cars.Any(car => car.Name.Equals(auto[0])) to see if theres no car within your collection where the predicate applies.

Upvotes: 1

Related Questions