开发者

How do I add a list object to class using lambda?

开发者 https://www.devze.com 2022-12-14 09:55 出处:网络
Say I have a class with 2 properties class TestClass { public int propertyOne {get;set;} public List<int> propertyTwo {get; private set;}

Say I have a class with 2 properties

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

Using linq, I am trying to create a list of TestClass as follows:

var results = from x in MyOtherClass
       开发者_JAVA百科       select new TestClass()
              {
                  propertyOne = x.propertyFirst,
                  propertyTwo = x.propertyList
              };

propertyTwo = x.propertyList actually throws an error, with the squiggly red underline.

How can I implement the equivalent of the propertyTwo.AddRange(other) in this case?

Cheers


As others have said you can't set the propertyTwo that way since its declared private. If you just want to set it on construction you could add a second constructor that allows you to pass an initial list, giving you:

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
};


As Forgotten Semicolon said above, it seems like the issue here is that your propertyTwo has a private setter.

Try changing your code in TestClass to be :

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

I don't believe you can initialize properties that are set as private using Asymmetric Accessor Accessibility.


Yes accessibility is the issue here. If you don't want a public setter, you could add a method SetPropertyList() to set the value, effectively doing the same thing in a different way.

0

精彩评论

暂无评论...
验证码 换一张
取 消