We help IT Professionals succeed at work.

C# - getting associated values from a class

skij
skij asked
on
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

Comment
Watch Question

Retired
Distinguished Expert 2017
Commented:
Something like this should work.

foreach( cat theCat in myCats)
{
    Console.WriteLine("The age of {0} is : {1} ", theCat.Name, theCat.Age);
}

Author

Commented:
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.
AndyAinscowFreelance programmer / Consultant
Commented:
Looping is the only way (even if you don't do the loop yourself).  Use what is suggested, just add an extra test to check the name is what you want.


ps.  A dictionary collection (instead of a list) allows you to select an item rapidly without having to loop
           foreach (Cat thisCat in myCats)
            {
                if (thisCat.Name.Equals("Whiskers"))
                {
                    Console.WriteLine("The age of Whiskers is: " + thisCat.Age);
                }

            }

Open in new window

Author

Commented:
Thank you.  I have asked a related question here:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_28643971.html
Fernando SotoRetired
Distinguished Expert 2017

Commented:
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