2013-03-25 70 views
3

我有列表:添加空元素列出

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

將元素添加到列表的正確方法是什麼?

回答

2

您需要聲明lst行與AsEnumerable()更換ToList()

問題是lst類型爲List<anonymous type>,但Union返回IEnumerable<anonymous type>。不能將IEnumerable<T>分配給List<T>類型的變量。

使用AsEnumerable()使lst變量的類型IEnumerable<anonymous type>

0

如何只:

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

只添加工作,如果地表溫度T和LST是一個List 2013-03-25 11:38:12

+0

@cad:這個評論並沒有真正意義。 – 2013-03-25 11:39:58

+0

我想說的是,lst是一個泛型和.ADD方法接受作爲參數只有類型:http://msdn.microsoft.com/en-us/library/3wcytfd1.aspx – 2013-03-25 11:42:24

2

你的最後一行更改爲使用的AddRange方法

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

你只需調用'lst.AddRange'。您不必將結果重新分配給'lst' ...實際上,您不能因爲.Add和'.AddRange'返回結果爲void。 – 2013-03-25 11:38:43

+0

你是100%正確的:)。我在複製原始代碼時感到困惑。事實上,這是我常犯的錯誤... – 2013-03-25 11:39:36

+0

@Grant謝謝。沒有重新分配它是有效的。 – Andrey 2013-03-25 11:56:37

1

嘗試AddRange()方法,它採取的IEnumerable<T>,而不是什麼你的類型,FirstList<T>.Union(SecondList<T>)

lst.AddRange(yourIEnumerable); 
+0

謝謝。這個變體工作正常。 – Andrey 2013-03-25 12:00:42