【问题标题】:returning NULL from an IEnumerable method if no results were found如果未找到结果,则从 IEnumerable 方法返回 NULL
【发布时间】:2020-02-05 02:43:51
【问题描述】:

我正在使用 Automapper 和带有 Xml 序列化的类来生成 XML 文件。

在这个方法中,它返回一个 IEnumerable 给 Automapper,然后 Automapper 写出一系列<GenerationMethod>...</GenerationMethod> XML 元素。

它确实有效,但是,如果它返回一个空的 IEnumerable,因为没有找到结果,我会得到像这样的空 XML 标记:

<GenerationMethod />

有没有办法返回 NULL 以免生成空的 XML 标记?

方法如下。谢谢!

public static IEnumerable<GenerationMethod> GetGenerationMethod(this DungeonGrid monster)
{

    var customMonster = monster.Stats
            .Where(e => e.Stat.Category.IsActive);

    if (monster.MonsterType.DestructionMethod.StartsWith("TEST"))
    {
        yield return new GenerationMethod(monster.MonsterType.DestructionMethod);
    }

    foreach (Stat in customMonster)
    {
        if (DungeonLookupByStatId.ContainsKey(customMonster.MonsterType.Id))
            yield return DungeonLookupByStatId[customMonster.MonsterType.Id];
    }
}

【问题讨论】:

    标签: c# asp.net-core automapper ienumerable


    【解决方案1】:

    您的最终目标是不要在 XML 中包含 GenerationMethod 标记,以防 IEnumerable 为空。

    所以我建议你正确处理这个问题,不要改变返回 IEnumerable 的方法。
    IEnumerable 就像薛定谔的猫。它有所有项目,根本没有项目,只有当您实际枚举时,您才会确切知道它将产生哪些项目。
    所以返回 null 而不是 IEnumerable 将违背 IEnumerable 的目的。

    所以,要回答您的问题,请创建您自己的 xml 序列化程序(Here is an answer on SO about how you can achieve that,或者只是查找它。它应该非常简单)。您需要做的就是更改 IEnumerable 写入 XML 的方式。
    逻辑应该很简单:

    1. 在您的IEnumerable 上调用.ToList() 扩展方法来枚举它。
    2. 如果列表有项目,则创建标签并以常规方式添加标签。
    3. 如果列表为空,则不执行任何操作。

    我希望它能为您提供您正在寻找的方向。

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2011-02-08
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2023-02-13
      相关资源
      最近更新 更多