2009-12-21 120 views
1

說我有2個屬性如何使用lambda將類列表對象添加到類中?

class TestClass 
{ 
    public int propertyOne {get;set;} 
    public List<int> propertyTwo {get; private set;} 
    public TestClass() 
    { 
     propertyTwo = new List<int>(); 
    } 
} 

使用LINQ,我想如下創建的TestClass列表的類:

var results = from x in MyOtherClass 
       select new TestClass() 
       { 
        propertyOne = x.propertyFirst, 
        propertyTwo = x.propertyList 
       }; 

propertyTwo = x.propertyList居然拋出一個錯誤,帶着紅色的下劃線。

如何在這種情況下實現propertyTwo.AddRange(other)的等價物?

乾杯

+3

是propertyTwo應該有一個'私人'二傳手。 – 2009-12-21 23:09:23

+0

是的,並在班級建設期間初始化。 在正常情況下,它會是這樣的: TestClass newClass = new TestClass(); newClass.propertyTwo.AddRange(new List (){1,2,3,4}); – Joshscorp 2009-12-21 23:12:25

回答

3

正如其他人所說,你不能設置propertyTwo,因爲它宣佈爲私人。如果你只是想將其放置在建築,你可以添加第二個構造函數允許你傳遞的初步清單,讓您:

class TestClass 
{ 
    public int propertyOne {get;set;} 
    public List<int> propertyTwo {get; private set;} 

    public TestClass() : this(new List<int>()) { } 
    public TestClass(List<int> initialList) 
    { 
     propertyTwo = initialList; 
    } 
} 
... 
var results = from x in MyOtherClass 
select new TestClass(x.propertyList) 
{ 
    propertyOne = x.propertyFirst 
}; 
2

由於忘記分號上面說的,好像這裏的問題是,你的propertyTwo設有私人二傳手。

試着改變你的代碼TestClass是:

public List<int> propertyTwo {get; set;} 

我不相信你可以初始化使用非對稱訪問器可訪問性設置爲私有財產。

1

是無障礙環境是這裏的問題。如果你不需要公共setter,你可以添加一個方法SetPropertyList()來設置值,有效地以不同的方式做同樣的事情。