Store three elements in one variable in C#

1.2k Views Asked by At

I have the following data set and would like to store the three arrays in one variable for lookup.

name         date          size  
aaa          201201        0.82  
bbb          201306        1.04  
ccc          201209        0.91   
................

How do I store all the information in one variable? There are hundreds of rows. I am working with C#. I need to be able to search through the variable. For example, if time = 201201, name = aaa, then the size is 0.82.

2

There are 2 best solutions below

6
Thorsten Dittmar On BEST ANSWER

EDIT: I modified my original answer to be able to search by name and date and get size.

You could use the Tuple class like this:

Dictionary<Tuple<string, DateTime>, float> dict = new Dictionary<Tuple<string, DateTime>, float>();
dict[new Tuple<string, DateTime>("aaa", DateTime.Now)] = 0.82f;

This approach assumes that the combination of name and date is unique, like an index. You can easily search by index, then.

If you need to search name/date by size, though, the wrapper class approach Adrian Carneiro suggested is probably better.

0
Adriano Carneiro On

Best way? Create a wrapper class, store in a List, query using Linq to objects:

public class YourStuff{
    public string Name;
    public DateTime Date;
    public double Size;
}

...

List<Stuff> myStuff = new List<Stuff>();

//then load from DataSet, DataTable, etc.

Some Linq examples:

var greaterThanOne = myStuff.Where(stuff => stuff.Size > 1);
var greaterThanOneCount = myStuff.Count(stuff => stuff.Size > 1);
var sumOfAllSizes = myStuff.Sum(stuff => stuff.Size);

With Linq to objects you can find, sort, slice and dice, group by, you name it.