I have 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();
I need to add empty element to this list. I try this variant:
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);
But get error:
Cannot implicitly convert type System.Collection.Generic.IEnumerable to System.Collection.Generic.List
on last line.
What is correct way to add element to list?
You need to replace ToList()
with AsEnumerable()
in the line that declares lst
.
The problem is that lst
is of type List<anonymous type>
but Union
returns IEnumerable<anonymous type>
. An IEnumerable<T>
can't be assigned to a variable of type List<T>
.
Using AsEnumerable()
makes the lst
variable of type IEnumerable<anonymous type>
.
Change your last line to use AddRange method:
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.AddRange(Filials);