acoder
acoder

Reputation: 697

c# collections and array with textual keys and values

I can add rows of data to a datatable.

DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Id");
dt.Columns.Add("Title");
dt.Columns.Add("Description");

DataRow r = dt.NewRow();
r["Id"] = 1;
r["Title"] = "Article Title";
r["Description"] = "Article Description";
dt.Rows.Add(r);

Then output the necessary cell value.

MessageBox.Show(dt.Rows[0]["Title"].ToString());

So it's a kind of array ( that contains rows ) of arrays ( each one having 3 textual keys and 3 textual values ).


Question:

How can I use Collection variables to achieve this without a datatable?
Or maybe you could suggest any other type of data which is more appropriate.

Upvotes: 1

Views: 39

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27871

You can create a class to represent your object like this:

public class MyData //You can name this whatever makes sense in your case
{
    public int Id {get;set;}
    public string Title {get;set;}
    public string Description {get;set;}
}

And then you can create a List<MyData> like this:

List<MyData> list = new List<MyData>();

list.Add(
    new MyData
    {
        Id = 1,
        Title = "Article Title",
        Description = "Article Description"
    });

And access it like this:

MessageBox.Show(list[0].Title);

Upvotes: 3

Related Questions