2014-09-25 77 views
1

我想每個序列每個列表集合中的每個對象的Object小號如何通過列表的泛型列表內循環

泛型列表裏面作爲一個例子,我可以通過每個列表對象alist迭代通用內部名單temp_list,但因爲我不知道v對象是什麼,直到運行時我不能引用它的列表:

List<AObj> alist = new List<AObj>(); 
List<BObj> blist = new List<BObj>(); 

// .. objects initialized here, plugged into respective lists, etc. 

List<Object> temp_list = new List<Object>(); 
temp_list.Add(alist); 
temp_list.Add(blist); 

foreach (var v in temp_list) 
{ 
    // Here I want to iterate through the list in each v 
    /* 
    foreach (var w in v) <-- This obviously doesn't work because the compiler 
          doesn't know what v is until run-time 
    */ 
} 

alistblist剛剛基本對象:

class AObj 
{ 
    public string Property1 { get; set; } 
    public string Property2 { get; set; } 
} 

class BObj 
{ 
    public string Property3 { get; set; } 
    public string Property4 { get; set; }  
} 

有沒有一種方法,我可以有一個雙重foreach,讓我迭代通用列表中的列表中的每個對象。

由於編譯器直到運行時才知道v,所以它幾乎停滯在正確的狀態。

回答

1

如果您確信它是那麼可重複的鑄造會工作

foreach (var v in temp_list) 
{ 
    // Here I want to iterate through the list in each v 
    foreach (var w in v as IEnumerable) //casting to IEnumerable will let you iterate 
    { 
     //your logic 
    } 
} 

或者你可以改變外部列表類型,以避免

List<Object> temp_list = new List<Object>(); 
鑄造

List<IEnumerable> temp_list = new List<IEnumerable>(); 

,如果它是不可能的,那麼也許增加一個檢查之前,迭代應使代碼的安全,而不是object

foreach (var v in temp_list) 
{ 
    // Here I want to iterate through the list in each v 
    //casting to IEnumerable will let you iterate 
    IEnumerable list = v as IEnumerable; 
    //check if successful 
    if(list != null) 
    { 
     foreach (var w in list) 
     { 
      //your logic 
     } 
    } 
    else 
    { 
     //else part if needed 
    } 
} 
0

您必須聲明你的臨時列表爲IEnumerable<object>列表。這樣做是如下:

var alist = new List<AObj>(); 
var blist = new List<BObj>(); 

// .. objects initialized here, plugged into respective lists, etc. 

var temp_list = new List<IEnumerable<object>>(); 

temp_list.Add(alist); 
temp_list.Add(blist); 

foreach (var v in temp_list) 
{ 
    foreach (var x in v) 
    { 

    } 
} 
0

使用LINQ ...

List<AObj> alist = new List<AObj>(); 
List<BObj> blist = new List<BObj>(); 

// .. objects initialized here, plugged into respective lists, etc. 

List<object> temp_list = new List<object>(); 

temp_list.Add(alist); 
temp_list.Add(blist); 

var allObjects = temp_list 
    .Select(l => l as IEnumerable<object>) // try to cast to IEnumerable<object> 
    .Where(l => l != null)     // filter failed casts 
    .SelectMany(l => l);     // transform the list of lists into a single sequence of objects 

foreach (var o in allObjects) 
{ 
    // enumerates objects in alist and blist. 
}