我有 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/