Andrey
Andrey

Reputation: 517

Add empty element to list

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?

Upvotes: 4

Views: 16018

Answers (4)

Jakub Konecki
Jakub Konecki

Reputation: 46008

How about just:

Filials.Add(new { Name = string.Empty, FilialId = (Guid?)null })

Upvotes: 0

LukeHennerley
LukeHennerley

Reputation: 6444

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

lst.AddRange(yourIEnumerable);

Upvotes: 2

Oscar Foley
Oscar Foley

Reputation: 7025

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

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174447

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

Upvotes: 3

Related Questions