I am new to asp.net with C#. Now I need a solution for one issue.
In PHP I can create an array like this:
$arr[] = array('product_id' => 12, 'process_id' => 23, 'note' => 'This is Note');
//Example
Array
(
[0] => Array
(
[product_id] => 12
[process_id] => 23
[note] => This is Note
)
[1] => Array
(
[product_id] => 5
[process_id] => 19
[note] => Hello
)
[2] => Array
(
[product_id] => 8
[process_id] => 17
[note] => How to Solve this Issue
)
)
I want to create the same array structure in asp.net with C#.
Please help me to solve this issue.
What are a key and value in an array? Keys are indexes and values are elements of an associative array. Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop.
Assigning Values to an Array int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks; When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair. d.
Use a Dictionary<TKey, TValue>
for quick lookups of a value (your object) based on a key (your string).
var dictionary = new Dictionary<string, object>();
dictionary.Add("product_id", 12);
// etc.
object productId = dictionary["product_id"];
To simplify the Add
operation, you could use collection initialization syntax such as
var dictionary = new Dictionary<string, int> { { "product_id", 12 }, { "process_id", 23 }, /* etc */ };
Edit
With your update, I would go ahead and define a proper type to encapsulate your data
class Foo
{
public int ProductId { get; set; }
public int ProcessId { get; set; }
public string Note { get; set; }
}
And then create an array or list of that type.
var list = new List<Foo>
{
new Foo { ProductId = 1, ProcessId = 2, Note = "Hello" },
new Foo { ProductId = 3, ProcessId = 4, Note = "World" },
/* etc */
};
And then you have a list of strongly-typed objects you can iterate over, bind to controls, etc.
var firstFoo = list[0];
someLabel.Text = firstFoo.ProductId.ToString();
anotherLabel.Text = firstFoo.Note;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With