ThomasK
ThomasK

Reputation: 155

Retrieve values corresponding to numbers

I have a list of numbers, where each one has two corresponding numbers like this:

1: 30 and 60
2: 70 and 100
3: 120 and 150

I would like to get both numbers corresponding to a given number. For example, if I look up 2, I would retrieve 70 and 100.

What is the best data type to store and retrieve this information?

Upvotes: 0

Views: 90

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

This is good example of Encapsulation pillar of OOP:

Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object.

You can create a class with three properties Id, Number1 and Number2 respectively. In this way it will be easier for you to keep relationship between all three numbers

public class Numbers
{
   public int Id { get; set; }
   public int Number1 { get; set; }
   public int Number2 { get; set; }

   public Numbers(int id, int num1, int num2)
   { 
       this.Id = id;
       this.Number1 = num1;
       this.Number2 = num2;
   }
}

You have list of Numbers like,

 List<Numbers> NumberList = new List<Numbers>()
 { 
      new Numbers(1, 30, 60),
      new Numbers(2, 70, 100),
      new Numbers(3, 120, 150)
 }

Now if you want to filter it by pair by Id, then

 using System.Linq; 
 ...
 var result = NumberList.FirstOrDefault(x => x.Id == 3);
 Console.WriteLine($"{result.Id}: {result.Number1} and {result.Number2}");

Output:

3: 120 and 150.

What is the best data type to store / retrieve this information?

To store numeric data, C# provide short, int, long, float, double datatypes. You can choose any of the data type as per your requirement.

Upvotes: 3

DKar
DKar

Reputation: 504

You can use a dictionary with tuples

var dic = new Dictionary<int, Tuple<int, int>>();
dic.Add(1, Tuple.Create(30, 60));
dic.Add(2, Tuple.Create(70, 100));
dic.Add(3, Tuple.Create(120, 150));

Then if for example you want to get both numbers corresponding to for example 3

dic.TryGetValue(3, out Tuple<int, int> res);
var firstNumber= res.Item1; //this should be 120
var secondNumber = res.Item2; //this should be 150

Upvotes: 2

Related Questions