C# C语言中字典不可变的问题选择#
在这种情况下,不确定字典的最佳替代方案是对象还是数组。 我需要根据id/键是否存在来更改字典的值(或其他任何内容),如果在中解析的id确实存在,则添加到现有值中,而不是添加键/id-最好的替代方案是什么 代码C# C语言中字典不可变的问题选择#,c#,dictionary,C#,Dictionary,在这种情况下,不确定字典的最佳替代方案是对象还是数组。 我需要根据id/键是否存在来更改字典的值(或其他任何内容),如果在中解析的id确实存在,则添加到现有值中,而不是添加键/id-最好的替代方案是什么 代码 Dictionary<int, int> total = new Dictionary<int, int>(); // elsewhere in a function... ArrayManager(total, id, value); publi
Dictionary<int, int> total = new Dictionary<int, int>();
// elsewhere in a function...
ArrayManager(total, id, value);
public void ArrayManager(Dictionary<int,int> items, int id, int val)
{
int i = 0;
bool found = false;
foreach(var item in items)
{
if(item.Key == id)
{
item.Value += val; // immutable issue stops this from working
found = true;
break;
}
}
if(found == false)
{ // do something }
}
字典总数=新字典();
//函数中的其他位置。。。
ArrayManager(总计、id、值);
public void数组管理器(字典项、int-id、int-val)
{
int i=0;
bool-found=false;
foreach(项目中的var项目)
{
如果(item.Key==id)
{
item.Value+=val;//不可变问题会停止此操作
发现=真;
打破
}
}
if(found==false)
{//做点什么}
}
我相信您要做的是:
if(item.Key == id)
{
items[item.Key]+= val;
}
我相信你想做的是:
if(item.Key == id)
{
items[item.Key]+= val;
}
如果试图增加给定键标识的值:
public void ArrayManager(Dictionary<int,int> items, int id, int val)
{
int currentVal = 0;
if (items.TryGetValue(id, out currentVal))
{
int newVal = currentVal + val;
items[id] = newVal;
// Do something else
}
public void数组管理器(字典项、int-id、int-val)
{
int currentVal=0;
if(items.TryGetValue(id,out currentVal))
{
int newVal=currentVal+val;
items[id]=newVal;
//做点别的
}
如果试图增加给定键标识的值:
public void ArrayManager(Dictionary<int,int> items, int id, int val)
{
int currentVal = 0;
if (items.TryGetValue(id, out currentVal))
{
int newVal = currentVal + val;
items[id] = newVal;
// Do something else
}
public void数组管理器(字典项、int-id、int-val)
{
int currentVal=0;
if(items.TryGetValue(id,out currentVal))
{
int newVal=currentVal+val;
items[id]=newVal;
//做点别的
}
您不应该修改字典的键。所有foreach块都可以替换为TryGetcall@DanielA.White-我没有修改键,只修改所述的值。代码中未显示(将编辑)'因为我是山雀。@JammAndTea您有item.Key+=val;
您不应该修改字典的键。您所有的foreach块都可以替换为TryGetcall@DanielA.White-我没有修改键,只修改所述的值。代码中未显示(将编辑)'因为我是山雀。@JammAndTea你有item.Key+=val;
你的意思是“+=val”?哦,我认为字典是完全不可变的-谢谢你,我会检查。@JammAndTea它们不是不可变的,否则Add将返回一个新字典,而不是无效的。你的意思是“+=val”?哦,我认为字典是完全不可变的-谢谢,我会检查。@JammAndTea它们不是不可变的,否则Add将返回一个新字典,而不是void谢谢-这与apomene的答案不一样吗?有什么好处吗?@JammAndTea字典可以很快地检索与键相关的值,但是如果你正在枚举在它们上面(foreach)你失去了解释的所有好处谢谢-这不是和apomene的答案一样吗?有好处吗?@JammAndTea字典检索与键相关的值非常快,但是如果你在它们上面(foreach)枚举,你失去了解释的所有好处谢谢!