2012-06-08 45 views
0

我使用EF,所以我的子集合是EntityCollection類型的< T>。如果屬性「Children」爲EntityCollection < T>如何將查詢結果IEnumerable < T>轉換爲EntityCollection < T>?如何將IEnumerable <T>的子集合轉換爲EntityCollection <T>?

感謝

var list = element.Elements(ns + "Parent") 
     .Select(parsedXml => 
         Children = parsedXml.Elements(ns + "Child") 
         .Select(child => new Child { 
                 Id = Convert.ToInt32(child.Attribute("id").Value) 
                }) 
         }); 

回答

2

既然你已經使用LINQ,你可以通過創建一個擴展方法相同型號做到這一點:

public static EntityCollection<T> ToEntityCollection<T>(this IEnumerable<T> source) 
{ 
    var col = new EntityCollection<T>(); 
    foreach (var item in source) 
    { 
     col.Add(item); 
    } 
    return col; 
} 

加入.ToEntityCollection()到底然後用這個在原來的LINQ語句。

+0

+1使用擴展方法,愛em! – Joe

+0

感謝您的幫助 – MikeW

0

沒有可用的直接鑄造。您將需要遍歷集合並添加到新的實體集合中。

var eCollection = new EntityCollection<T>();  
foreach (var child in list) 
{ 
    eCollection.Add(child); 
} 
+1

這是低效率的,因爲它遍歷列表兩次。 –

+0

@ DanielA.White,我在這裏只能看到一個list列表...... –

+0

@ThomasLevesque我編輯了我的帖子;我以前用這個代替了可枚舉列表中的foreach list.ToList()。ForEach(a => eCollection.Add(a));' –

相關問題