Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 设置IDictionary的所有值_C#_.net - Fatal编程技术网

C# 设置IDictionary的所有值

C# 设置IDictionary的所有值,c#,.net,C#,.net,“重置”结构类型的词典的最佳方法是什么(将所有值设置为true或false)。目前我正在使用ToDictionary()扩展方法。有没有办法通过重用当前实例来做到这一点 此代码引发异常: [TestFixture] public class Sample { [Test] public void SampleTest() { var dictionary = new Dictionary<int, bool>{{1, false}, {2, t

“重置”结构类型的
词典的最佳方法是什么(将所有值设置为
true
false
)。目前我正在使用
ToDictionary()
扩展方法。有没有办法通过重用当前实例来做到这一点

此代码引发异常:

[TestFixture]
public class Sample
{
    [Test]
    public void SampleTest()
    {
        var dictionary = new Dictionary<int, bool>{{1, false}, {2, true}, {3, false}};
        foreach (var key in dictionary.Keys)
        {
            dictionary[key] = true;
        }

        Assert.That(dictionary[3], Is.True);
    }
}
[TestFixture]
公共类样本
{
[测试]
公共无效样本测试()
{
var dictionary=newdictionary{{1,false},{2,true},{3,false};
foreach(dictionary.Keys中的var键)
{
字典[键]=真;
}
Assert.That(字典[3],Is.True);
}
}

< /代码>

作为一个旁白,您可能希望考虑使用BITARORD类(System .Copy.BitArray)。它有一个SetAll方法,可以将所有位设置为true或false:

BitArray ba = new BitArray(8);  //BitArray with 8 bits

ba[3] = true;  //set some bits
ba[6] = true;

ba.SetAll(false);  //Clear all

如果你不需要字典,你可以考虑这个类。

你能澄清或添加几行代码吗?从听起来,我想你想把字典里的每一项都设置为一个特定的值,除非有一个内置的方法,否则对我来说这听起来像是一个foreach循环……循环字典里的所有键,并将它们的值设置为
true
false
?我怀疑是否有更有效的方法,而且它的可读性可能不会比尝试相同的复杂LINQ语句差。@Kendrick,是的,我想将所有值设置为true,foreach循环抛出一个修改的集合Exception我没有做任何测试,但我认为这是不必要的创建一个循环列表,在KeyValuePair上循环会更快:
foreach(字典中的var-kvp)dictionary[kvp.Key]=true
@manixrock,您的建议会引发相同的异常,因为它试图修改正在循环的集合。调用
ToList
的目的是创建并循环一个完全不同的集合。+1表示BitArray,但在这种情况下,它必须是一个字典(非序列ID)。
BitArray ba = new BitArray(8);  //BitArray with 8 bits

ba[3] = true;  //set some bits
ba[6] = true;

ba.SetAll(false);  //Clear all