Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects with custom index

Tags:

c#

I have these two classes:

public class Message
{
    string Message;
    string Code;
}

public class MessageInitializer
{
    DataSet ds;
    DataRow dr;
    message[] ms;
}

I want to create a constructor in MessageInitializer like this:

MessageInitializer()
{
    this.ms = new Message[ds.Tables[0].Rows.Count];
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        dr = ds.Tables[0].Rows[i];
        ms[(string)dr.ItemArray[0]] = (string)dr.ItemArray[1];
    }
}

But array's index must be int type. I have no idea how to work this out:

ms[(string)dr.ItemArray[0]] = (string)dr.ItemArray[1];

Update:

Code format is a string like this: [001-001-001], so I can't convert it to integer.

like image 714
Mohammad Avatar asked Jul 26 '15 04:07

Mohammad


People also ask

Can you use indexOf for an array of objects?

The Array. indexOf() method returns the index of the first matching item in an array (or -1 if it doesn't exist). var wizards = ['Gandalf', 'Radagast', 'Saruman', 'Alatar']; // Returns 1 wizards.

How do you add an object to a specific index in an array?

Using array.splice() method is usually used to add or remove items from an array. This method takes in 3 parameters, the index where the element id is to be inserted or removed, the number of items to be deleted and the new items which are to be inserted.

Can you index an array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Can you index an array in JavaScript?

An item in a JavaScript array is accessed by referring to the index number of the item in square brackets. We know 0 will always output the first item in an array. We can also find the last item in an array by performing an operation on the length property and applying that as the new index number.


1 Answers

you don't need Message class any more. Using a dictionary as follows solves the problem :

public class MessageInitializer
{
    DataSet ds;
    DataRow dr;
    Dictionary<string, string> ms;
    public MessageInitializer()
    {
        this.ms = new Dictionary<string,string>(ds.Tables[0].Rows.Count);
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            dr = ds.Tables[0].Rows[i];
            ms[(string)dr.ItemArray[0]] = (string)dr.ItemArray[1];
        }
    }
}

I hope this would be helpful.

like image 152
Mohammad Chamanpara Avatar answered Oct 30 '22 11:10

Mohammad Chamanpara