Add empty element to list

c# entity-framework linq

Question

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?

1
3
3/25/2013 11:33:29 AM

Accepted Answer

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>.

2
3/25/2013 11:34:29 AM

Popular Answer

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);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow