gpt4 book ai didi

c# - ASP .NET 中的数组键值与 C#

转载 作者:可可西里 更新时间:2023-11-01 08:02:12 25 4
gpt4 key购买 nike

我是使用 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
)

)

我想用 C# 在 asp.net 中创建相同的数组结构。

请帮我解决这个问题。

最佳答案

使用 Dictionary<TKey, TValue>用于基于键(您的字符串)快速查找值(您的对象)。

var dictionary = new Dictionary<string, object>();
dictionary.Add("product_id", 12);
// etc.

object productId = dictionary["product_id"];

为了简化 Add操作,您可以使用集合初始化语法,例如

var dictionary = new Dictionary<string, int> { { "product_id", 12 }, { "process_id", 23 }, /* etc */ };

编辑

随着你的更新,我会继续定义一个合适的类型来封装你的数据

class Foo
{
public int ProductId { get; set; }
public int ProcessId { get; set; }
public string Note { get; set; }
}

然后创建该类型的数组或列表。

var list = new List<Foo>
{
new Foo { ProductId = 1, ProcessId = 2, Note = "Hello" },
new Foo { ProductId = 3, ProcessId = 4, Note = "World" },
/* etc */
};

然后你有一个强类型对象列表,你可以迭代、绑定(bind)到控件等。

var firstFoo = list[0];
someLabel.Text = firstFoo.ProductId.ToString();
anotherLabel.Text = firstFoo.Note;

关于c# - ASP .NET 中的数组键值与 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7970506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com