简体   繁体   English

C#-在字典中设置Dictionary'Key值的最佳方法?

[英]C# - Best way to set Value of Dictionary'Key in Dictionary?

I have a Dictionary as below: 我有以下Dictionary

var mapStudent = new Dictionary<string, Dictionary<List<Student>, Boolean>>;

Now I want to set Boolean = true , I wrote below: 现在我想设置Boolean = true ,我在下面写道:

...
var key_value = mapStudent.Where(st => st.Key == classID).First();
var listStudent_EditFlag = key_value.Value;
foreach (KeyValuePair<List<Student>, Boolean> pair in listStudent_EditFlag)
{
    listStudent_EditFlag[pair.Key] = true;
    break;
}
...

Doing so is the better practice? 这样做是更好的做法吗? Thanks in advance. 提前致谢。

I'm sorry man you ain't going far with your code if you try to deal with such a structure. 抱歉,如果您尝试处理这样的结构,那么您的代码就走得太远了。 Since you are talking about best practices, I suggest you to rethink your structure to avoid endless headaches. 由于您在谈论最佳实践,因此建议您重新考虑自己的结构,以避免无休止的头痛。

If you need to map a list of students to a single property, then maybe you actually need an abstraction over that list of students... i bet we are talking about a class (a school class). 如果您需要将一个学生列表映射到一个属性,那么也许您实际上需要对该学生列表进行抽象...我敢打赌,我们正在谈论的是课堂(学校课程)。 This way if you have to deal with a new property of the class tomorrow, you don't have to rewrite all of your code, but just add a property to the SchoolClass class. 这样,如果您明天必须处理该类的新属性,则不必重写所有代码,而只需向SchoolClass类添加一个属性。 And to initilize all of your booleans to true you just need to set true as the default value for your property inside the constructor of SchoolClass. 要将所有布尔值初始化为true,您只需要在SchoolClass 构造函数中将属性的默认值设置为true即可。

Thinking the same way you probably need to abstract a list of ShoolClass mapped to a string to something like a School. 以同样的方式思考,您可能需要将映射到字符串的ShoolClass列表抽象为School。

This way the code simplifies and it easier to leverage the power of Linq to perform complex operation and other technologies and of course present the data. 这样,代码得以简化,并且更容易利用Linq的功能来执行复杂的操作和其他技术,并且当然可以显示数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM