如何使用 LINQ 创建对象并初始化该对象中的列表? (此外,我正在尝试创建一个不可变对象(immutable对象)。)我正在访问 XML Web 服务。
例如,我有一个具有多个属性的类。但是,我在类里面也有一些私有(private)列表。
public class MyClass
{
public string SomeProperty { get; private set; }
public string AnotherProperty { get; private set; }
internal List<Result> ResultSet1 { get; set; }
internal List<Result> ResultSet2 { get; set; }
public IEnumerable<Result> GetResultSet1()
{
return ResultSet1;
}
//Constructor here to set the private properties eg: this.SomeProperty = someProperty;
//etc.
}
然后我有 Result.cs :
public class Result
{
public string YetAnotherProperty { get; private set; }
//etc.
}
到目前为止,我能够使用 LINQ 读取 XML 并创建一个“MyClass”对象,然后通过构造函数设置它的属性。但是,我也不知道如何:
- 初始化
List<Result>从 LINQ 查询中 - 如何更改
Result的属性在 LINQ 查询中的列表中
这是我目前拥有的 LINQ:
//Use the contents of XML nodes/elements as the arguments for the constructor:
var query = from i in document.Descendants("response")
select new MyClass
(
(string)i.Element("some").Element("property"),
(string)i.Element("another").Element("property")
)
我的问题:我对 LINQ 或使用 LINQ 创建对象的了解不够,不知道如何在我尝试创建的对象中初始化列表。我该怎么做呢?如何将项目添加到 ResultSet1来自 LINQ?
请您参考如下方法:
假设属性是可访问的,您可以通过常规对象初始化语法简单地设置属性。只需在 new 调用后添加一对大括号并设置属性。
var query =
from response in document.Descendants("response")
// for readability
let someProperty = (string)response.Element("some").Element("property")
let anotherProperty = (string)response.Element("another").Element("property")
select new MyClass(someProperty, anotherProperty)
{
ResultSet1 = response.Elements("someSet")
.Select(ss => new Result
{
YetAnotherProperty = (string)ss.Element("another")
.Element("property")
})
.ToList()
ResultSet2 = /* etc. */,
};
