c# - 字典中没有值
问题描述
所以我有一个 enumflag 系统,我需要在下拉列表中按麻醉品、非麻醉品、精神药物和非精神药物进行过滤。我的想法是将值放入字典中,并将它们的视图放入前端的选择列表中,但我无法配置字典以注册“[var] 的缺失”
如果我的字典结构如下:
private readonly Dictionary<int, string> _medicationDetails = new Dictionary<int, string>
{
{(int)PersonMedicationDescription.MedicationTags.NarcoticDrug, "Narcotic"},
{(int)PersonMedicationDescription.MedicationTags.PsychotropicDrug, "Psychotropic"}
};
我希望能够做到:
{(int)!PersonMedicationDescription.MedicationTags.NarcoticDrug, "non-Narcotic"},
或类似的规定。我在这里想念什么?有没有更好的方法来实现这一点?
编辑:
是一个布尔正确的方法。如果它只是一个布尔值,我知道该怎么做,但是如何让两者都填充列表?为了让一个工作,我认为这会工作:
ViewBag.IsNarcoticOptions = new[]
{
true,
false
}.ToSelectList(b => b.ToString(), b => b.ToString("Narcotic", "Non Narcotic"));
var isNarcotic = filters.IsNarcotic;
if (isNarcotic.HasValue)
{
query = isNarcotic.Value
? query.Where(rdq => (rdq.MedicationFlags & (int)PersonMedicationDescription.MedicationTags.NarcoticDrug) == (int)PersonMedicationDescription.MedicationTags.NarcoticDrug)
: query.Where(rdq => (rdq.MedicationFlags & (int)PersonMedicationDescription.MedicationTags.NarcoticDrug) == 0);
}
但是如何为另一组真/假做到这一点?
解决方案
似乎您正在处理标志:药物要么是要么Narcotic
不是Psychotropic
;标志可以组合:我们可以有Narcotic
and Psychotropic
( LSD
?) 或者没有Psychotropic
也没有Narcotic
(Aspirin)。如果您的标志很少(少于 64 个),您可以尝试将枚举设计为Flags
并摆脱字典
[Flags]
public enum MedicationTags {
None = 0,
Narcotic = 1,
Psychotropic = 1 << 1,
// SomeOtherKind = 1 << n // where n = 2, 3, 4 etc.
}
然后让我们为枚举实现一个扩展方法: Description
public static class MedicationTagsExtensions {
public static String Description(this MedicationTags value) {
return string.Join(", ",
(value.HasFlag(MedicationTags.Narcotic) ? "" : "non-") + "Narcotic",
(value.HasFlag(MedicationTags.Psychotropic) ? "" : "non-") + "Psychotropic"
);
}
}
所以当有药物种类时:
// Morphine is narcotic only
MedicationTags morphine = MedicationTags.Narcotic;
// LSD is both narcotic and psychotropic
MedicationTags lsd = MedicationTags.Narcotic | MedicationTags.Psychotropic;
// Good old aspirin is neither narcotic nor psychotropic
MedicationTags aspirin = MedicationTags.None;
你可以很容易地得到描述
Console.WriteLine(aspirin.Description());
结果:
non-Narcotic, non-Psychotropic
推荐阅读
- javascript - GraphQL Schema 缺少名称
- mysql - MariaDB:在插入触发器之前有条件地中止写入新记录
- r - 使用条件更改 R 中的列
- python - 使用 ConfigParser 读取 API 密钥
- python - 如何获取dataframegroupby左侧的数字对?大熊猫
- imagemagick - ImageMagick 边框
- python - 如何将一串 1 和 0 转换为处理傅立叶变换的信号?
- python - 如何将特定整数分配给单词中的单个字符?
- sql - 如何将 2 个相关子查询与联接和条件聚合一起使用
- javascript - 如何将返回的数据处理为需要添加到 apollo 和 reactjs 中的 useQuery 挂钩的未定义数据