2013-10-24 29 views
0

那麼,這個問題/疑問的標題,我認爲這是相當不言自明的,但這裏去的想法(使用簡單的術語): 我有文件(在一個項目中)包含一個類(每個)其中有對象和方法(來自模型),其中一個方法返回一個List。我想創建另一個類來生成一個包含上面提到的所有列表的新列表。如果這主要可能在C#中實現,那麼我將非常感謝您如何創建這個觀點。預先感謝提示,幫助和好意!如何從指定數量的模型/類創建列表的列表?

我希望你能理解我,因爲我在描述問題時很不好。 :d

+1

這將澄清,如果你表現出相關的類,列表和方法,以及一些樣本數據和期望的結果。 –

回答

0

什麼你要找的是的SelectMany:

#region Terrible Object 

var hasAllTheItems = 
     new[] 
     { 
       new[] 
       { 
         new 
         { 
           Name = "Test" 
         } 
       }, 
       new[] 
       { 
         new 
         { 
           Name = "Test2" 
         }, 
         new 
         { 
           Name = "Test3" 
         } 
       } 
     }; 

#endregion Terrible Object 

var a = hasAllTheItems.Select(x => x.Select(y => y.Name)); 
var b = hasAllTheItems.SelectMany(x => x.Select(y => y.Name)); 
var c = hasAllTheItems.Select(x => x.SelectMany(y => y.Name)); 
var d = hasAllTheItems.SelectMany(x => x.SelectMany(y => y.Name)); 

Assert.AreEqual(2, a.Count()); 
Assert.AreEqual(3, b.Count()); 
Assert.AreEqual(2, c.Count()); 
Assert.AreEqual(14, d.Count()); 

A: {{Test}, {Test2, Test3}}

B: {Test, Test2, Test3}

C: {{T, e, s, t}, {T, e, s, t, 2, T, e, s, t, 3}}

D: {T, e, s, t, T, e, s, t, 2, T, e, s, t, 3}

+0

嗯這對我來說是新的。我從來沒有面對過這種情況。我可以問你從哪裏得到這個想法嗎? –

+0

基本上,hasAllTheItems是包含字符串的通用項目集合的集合。選擇根據該集合中的每個項目生成項目集合,如同在A.在B中,SelectMany用於指定您需要每個單獨的元素,而不是每個內部對象一個列表。 – Magus