c# - 将空元素添加到列表

标签 c# linq entity-framework

我有 list :

var Filials = Db.FILIALS.AsEnumerable().Where(x => x.PREFIX > 0).Select(x => new { Name = string.Format("{0} {1}", x.PREFIX, x.NAME), FilialId = (Guid?)x.FILIALID }).OrderBy(x => x.Name).ToList();

我需要向这个列表中添加空元素。我试试这个变体:

var lst = new[] { new { Name = string.Empty, FilialId = (Guid?)null } }.ToList();
var Filials = Db.FILIALS.AsEnumerable().Where(x => x.PREFIX > 0).Select(x => new { Name = string.Format("{0} {1}", x.PREFIX, x.NAME), FilialId = (Guid?)x.FILIALID }).OrderBy(x => x.Name).ToList();
lst = lst.Union(Filials);

但是报错:

Cannot implicitly convert type System.Collection.Generic.IEnumerable to System.Collection.Generic.List

在最后一行。

向列表添加元素的正确方法是什么?

最佳答案

您需要替换 ToList()AsEnumerable()在声明 lst 的行中.

问题是 lst类型为 List<anonymous type>但是Union返回 IEnumerable<anonymous type> .一个IEnumerable<T>不能分配给 List<T> 类型的变量.

使用 AsEnumerable()使 lst IEnumerable<anonymous type> 类型的变量.

关于c# - 将空元素添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15613863/

相关文章:

c# - Linq 多级内连接

c# - 如何在单元测试中使用 Moq 和 DbFunctions 来防止 NotSupportedException?

c# - 如何使用 Entity Framework 将我的更改保存到数据库?

.net - 检索新插入的项目时虚拟属性为 null

c# - 遍历 DbCommand 中的参数

c# - 用 Servicestack.Text 重构类型对象的属性

c# - 如何使用 C# 在 .Net 中的类型对象列表中选择对象属性的所有值

c# - 在哪里可以找到 System.Memory 文档?

c# - BitArray 以错误的方式返回位?

c# - 从单个值创建新 IEnumerable<T> 序列的最喜欢的方法?