rka*_*yan 13 c# asp.net arrays key
我是使用C#的ASP .NET新手现在我需要一个问题的解决方案
在PHP中我可以像这样创建一个数组
$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
)
)
Run Code Online (Sandbox Code Playgroud)
我想用ASP#在ASP .NET中创建相同的数组结构.
请帮我解决这个问题.提前致谢.
Ant*_*ram 26
使用a Dictionary<TKey, TValue>基于键(您的字符串)快速查找值(您的对象).
var dictionary = new Dictionary<string, object>();
dictionary.Add("product_id", 12);
// etc.
object productId = dictionary["product_id"];
Run Code Online (Sandbox Code Playgroud)
为简化Add操作,您可以使用集合初始化语法,例如
var dictionary = new Dictionary<string, int> { { "product_id", 12 }, { "process_id", 23 }, /* etc */ };
Run Code Online (Sandbox Code Playgroud)
编辑
有了您的更新,我会继续并定义一个适当的类型来封装您的数据
class Foo
{
public int ProductId { get; set; }
public int ProcessId { get; set; }
public string Note { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后创建该类型的数组或列表.
var list = new List<Foo>
{
new Foo { ProductId = 1, ProcessId = 2, Note = "Hello" },
new Foo { ProductId = 3, ProcessId = 4, Note = "World" },
/* etc */
};
Run Code Online (Sandbox Code Playgroud)
然后你有一个强类型对象列表,你可以迭代,绑定到控件等.
var firstFoo = list[0];
someLabel.Text = firstFoo.ProductId.ToString();
anotherLabel.Text = firstFoo.Note;
Run Code Online (Sandbox Code Playgroud)
string如果您正在寻找从到 的映射object:
Dictionary<string, object> map = new Dictionary<string, object> {
{ "product_id", 12 },
{ "process_id", 23 },
{ "note", "This is Note" }
};
Run Code Online (Sandbox Code Playgroud)
或者,也许您想要一个匿名类,如果这只是传递数据的一种方式:
var values = new {
ProductId = 12,
ProcessId = 23,
Note = "This is Note"
};
Run Code Online (Sandbox Code Playgroud)
这实际上取决于您想要实现的目标 - 更大的愿景。
编辑:如果您对多个值有相同的“键”,我可能会为此创建一个特定类型 - 目前尚不清楚这意味着代表什么类型的实体,但您应该创建一个类来对其进行建模,并且根据需要为其添加适当的行为。
| 归档时间: |
|
| 查看次数: |
52481 次 |
| 最近记录: |