首页 > 解决方案 > 字典中没有值

问题描述

所以我有一个 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);
            }    

但是如何为另一组真/假做到这一点?

标签: c#dictionaryenum-flagsenumdropdownlistfor

解决方案


似乎您正在处理标志:药物要么是要么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

推荐阅读