2012-04-13 73 views
0

假設我有一個這樣的類:創建一個包含其他列表元素引用的新列表?

class Base { } 
class A : Base { } 
class B : Base { } 
class C : Base { } 

和對象是這樣的:

A a = new A(); 
List<B> bs = new List<B>(); 
List<C> cs = new List<C>(); 

是否有可能創建一個包含其他列表的引用(這樣的變化反映在一個新的列表原項目 如:

void modifyContents(List<Base> allItems) { 
    //modify them somehow where allItems contains a, bs and cs 
} 

回答

3

您不能添加/刪除/在其他列表替換項目,但修改伊特ms在其他列表中。

List<Base> baseList = new List<Base>(); 
baseList.Add(a); 
baseList.AddRange(bs); 
baseList.AddRange(cs); 
// now you can modify the items in baseList 
2
  1. 使用LINQ Concat()兩個列表加入到單一IEnumerable<Base>
  2. 然後通過傳遞構造函數創建一個新的List<Base>例如先前加入一個

樣品

class Base 
{ 
    public string Id { get; set; } 
} 

List<B> bs = new List<B>() { new B() }; 
List<C> cs = new List<C> { new C(), new C() }; 
var common = new List<Base>(bs.OfType<Base>().Concat(cs.OfType<Base>())); 

// bs[0] will be updated 
common[0].Id = "1"; 

// cs[0] will be updated 
common[1].Id = "2"; 

// cs[1] will be updated 
common[2].Id = "3"; 
相關問題