Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

C# - getting associated values from a class

Using C#, in the example below, how can I get the associated age by a name?

For example, I want to print the age of the Cat named Whiskers.

using System;
using System.Linq;
using cAlgo.API;
using System.Collections.Generic;

namespace cAlgo.Robots
{
    [Robot()]
    public class DemoExample : Robot
    {
        List<Cat> myCats = new List<Cat> 
        {
            new Cat 
            {
                Name = "Sylvester",
                Age = 8,
                LuckyNumbers = {1,2,3,4,5}
            },
            new Cat 
            {
                Name = "Whiskers",
                Age = 2,
                LuckyNumbers = {22,11,3,5,2}

            },
            new Cat 
            {
                Name = "Sasha",
                Age = 13,
                LuckyNumbers = {122,1,3,25,1}
            }
        };


        protected override void OnStart()
        {

            Print("The age of Whiskers is: " + myCats);

        }

        protected override void OnTick()
        {

        }

    }
}

public class Cat
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<double> LuckyNumbers = new List<double>();
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of skij

ASKER

I only want to find the age of the Cat with the Name of "Whiskers".

There could be hundreds of cats so looping with foreach seems like an inefficient way to do this.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Then this should do it.
 int age = myCats.Where (c => c.Name == "Whiskers" ).FirstOrDefault ().Age;
 Console.WriteLine("The age of Whiskers is: " + age.ToString());

Open in new window