skij
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.
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>();
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you. I have asked a related question here:
https://www.experts-exchange.com/questions/28643971/C-Add-number-to-the-end-of-list-for-each-item.html
https://www.experts-exchange.com/questions/28643971/C-Add-number-to-the-end-of-list-for-each-item.html
Then this should do it.
int age = myCats.Where (c => c.Name == "Whiskers" ).FirstOrDefault ().Age;
Console.WriteLine("The age of Whiskers is: " + age.ToString());
ASKER
There could be hundreds of cats so looping with foreach seems like an inefficient way to do this.