BeginnedCSharp
BeginnedCSharp

Reputation: 39

Store three elements in one variable in C#

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.

Upvotes: 1

Views: 1284

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56717

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.

Upvotes: 4

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

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.

Upvotes: 12

Related Questions