Add empty element to list

11,369

Solution 1

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

Solution 2

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

Solution 3

Try the AddRange() method, it take's IEnumerable<T> instead of whatever your type is, FirstList<T>.Union(SecondList<T>).

lst.AddRange(yourIEnumerable);
Share:
11,369
Andrey
Author by

Andrey

I like summer.

Updated on June 04, 2022

Comments

  • Andrey
    Andrey almost 2 years

    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?