【问题标题】:C# How to "array.add" to an array of a dictionary?C#如何将“array.add”添加到字典数组中?
【发布时间】:2018-10-13 17:14:14
【问题描述】:

想象一下你有一本这样的字典:

Dictionary<int, int[]> dict = new Dictionary<int, int[]>();

所以我想做的是像普通数组一样“.add”到值。

我知道我可以像这样添加一个键和一个值:

dict.Add(0, new int[]{1, 2, 3, 4});

所以我有这个:Key=0, Value=[1, 2, 3, 4]

但是,如果我想在“Key=0”的值处添加“5”以使其看起来像 Key=0, Value=[1, 2, 3, 4, *5*],会发生什么?

【问题讨论】:

  • 你需要做的是提取数组并创建一个新数组,并在其末尾添加5,因为数组具有固定大小

标签: c# arrays dictionary


【解决方案1】:

要修改字典中的数组,您可以使用 LINQ 的Append()

dict[0] = dict[0].Append(5).ToArray();

但是如果你想修改它们,你不应该使用数组。请改用List&lt;T&gt;

var dict = new Dictionary<int, List<int>>();

dict.Add(0, new List<int> {1,2,3,4});

那你就可以在字典里面的列表上调用Append()了:

dict[0].Append(5);

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-10-29
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多