我正在尝试在包含元组列表的字典中添加值,但键是相同的。
我这样做
public struct MyStruct { public List> list1; }
public static Dictionary<long, MyStruct> myDictionary = new
Dictionary<long, MyStruct>();
funct()
{
if (myDictionary.ContainsKey(key))
{
myDictionary[key]= new MyStruct { list1 = s.list1 };
} // this block is been called from another function
}
但是因为我每次使用新的关键字都会被覆盖。但是我想补充一点,我没有另辟蹊径。请建议我另一种方式..因为我在网上搜索,但没有解决我的问题。
答案 0 :(得分:1)
不是每次都使用@Override
public boolean onCreateOptionsMenu(Menu menu) {
/* Inflate the menu; this adds items to the action bar if it is present. */
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
关键字,而是检查null,然后将值添加到结构内的列表中:
new
这样,如果您在字典结构中的列表中已有值,则新值也将添加到列表中。如果您没有任何价值且列表只是funct(){
if (myDictionary.ContainsKey(key))
{
if(myDictionary[key].list1 != null)
myDictionary[key].list1.AddRange(s.list1);
else myDictionary[key].list1 = new MyStruct { list1 = s.list1 };
} // this block is been called from another function
}
,则该程序将立即行动并创建新列表。
答案 1 :(得分:0)
如果要向Dictionary<TKey, TValue>
添加值,首先需要检查密钥是否已存在,因为密钥应该是唯一的,如果密钥不存在则可以设置值,否则如果密钥已经存在然后您使用该密钥获取值并更新它。检查下面的例子我希望它能帮助你理解它是如何工作的。您可以执行以下示例here
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
using System.Collections.Generic;
namespace Rextester
{
public class Program
{
public static Dictionary<long, MyStruct> myDictionary = new Dictionary<long, MyStruct>();
public static void Main(string[] args)
{
myDictionary.Add(1, new MyStruct { Numbers = new List<int> { 1, 2} });
Add(1, 3);
// printing out the values
foreach(KeyValuePair<long, MyStruct> number in myDictionary)
{
Console.WriteLine("Key: {0}", number.Key);
Console.WriteLine("Values:");
for(var i = 0; i < number.Value.Numbers.Count; i++)
{
Console.WriteLine(number.Value.Numbers[i]);
}
}
}
public static void Add(long key, int number)
{
if (myDictionary.ContainsKey(key))
{
var myStruct = myDictionary[key];
if (myStruct.Numbers != null)
{
myStruct.Numbers.Add(number);
}
}
else
{
myDictionary[key] = new MyStruct { Numbers = new List<int> { number }};
}
}
}
public struct MyStruct
{
public List<int> Numbers;
}
}