c# - 如何清空 IEnumerable 列表?

标签 c# asp.net-mvc

<分区>

我需要清空 IEnumerable 列表我尝试了很多东西,比如 null 但都没有用

这是我的模型的样子

public class NewsViewModel
{
    public NewsViewModel()
    {
        this.Categories = new List<Category>();
    }

    public int NewsId { get; set; }
    public string NewsTitle { get; set; }
    public string NewsBody { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}

if (!string.IsNullOrEmpty(SelectedCategoriesIds))
{
    List<Category> stringList = new List<Category>();
    stringList.AddRange(SelectedCategoriesIds.Split(',').Select(i => new Category() { CategoryId = int.Parse(i) }));
    model.Categories = stringList.AsEnumerable();
}
else
{
    model.Categories = null;
}

如何使 model.Categories 为空?

最佳答案

使用 Enumerable.Empty<T>() .

model.Categories = Enumerable.Empty<Category>();

The Empty() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

没有元素的可枚举序列不同于null .如果你返回 null对于 IEnumerable<T>然后尝试枚举它,您将收到一个 NullReferenceException .

另一方面,如果您返回 Enumerable.Empty<T>()并尝试枚举它,代码将执行得很好而不需要空检查,因为没有要枚举的元素。

值得注意的是Enumerable.Empty<T>()也比返回 new List<T>() 更有效率因为不需要分配新的列表对象。

您不能使用 .Clear()在这种情况下,因为你的 IEnumerable<T>是一个 projectable 序列,在枚举之前不会具体化。还没有什么要清除的。

最后,如下文所述,这只会更新这个 特定引用。如果还有其他内容也包含对您的 IEnumerable<T> 的引用, 它不会反射(reflect)变化,除非你特意传入 model.Categories通过ref .

或者,您可以转换为 List<Category>并调用.Clear() ,这将清除基础集合,更新所有引用。但是,如其他答案中所述,您还需要在执行此操作时执行显式空检查。但是请注意,这也是一个非常激进的操作。您不仅更新了这个实例,还更新了所有可能有也可能没有副作用的实例。您需要根据意图和需求确定哪个更合适。

关于c# - 如何清空 IEnumerable 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38490986/

相关文章:

c# - XDocument.Root.Element 返回 null

c# - 使用 AutoFaker 将 RuleFor 设置为 null

c# - 自定义类型数组的数组

javascript - 转换后的 razor 模型为 JS 对象属性为 null

c# - Entity Framework - 单个事务中的父子表更新

asp.net-mvc - MVC 4.0 使用 HttpResponse.RemoveOutputCacheItem 清除输出缓存

c# - 从代码访问表单的资源(resx 文件)

c# - 可编辑的 ComboBox 绑定(bind)和更新源触发器

javascript - 如何确保 JS 匿名对象继续映射到 POCO ViewModels

asp.net - NLog是否可以与customErrors一起使用?