Reputation: 6170
How do I use LINQ to create an object and also initialise list's within that object? (Also, I'm trying to create an immutable object.) I'm accessing an XML web service.
For example, I have a class with several properties. However, I also have some private lists within the class.
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.
}
And then I have Result.cs
:
public class Result
{
public string YetAnotherProperty { get; private set; }
//etc.
}
So far I am able to using LINQ to read the XML and create a "MyClass" object and then set it's properties via the constructor. However, I do not know how to either:
List<Result>
from within the LINQ queryResult
in the list from within the LINQ queryThis is the LINQ I have so far:
//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")
)
My question: I don't know enough about LINQ or creating objects with LINQ to know how to initialise lists within an object I am trying to create. How do I go about doing this? How do I add items to ResultSet1
from the LINQ?
Upvotes: 1
Views: 1289
Reputation: 25370
just add the object initializer after calling your constructor:
var query = from i in document.Descendants("response")
select new MyClass
(
(string)i.Element("some").Element("property"),
(string)i.Element("another").Element("property")
)
{
ResultSet1 = new List<Result>
{
new Result { YetAnotherProperty = ... },
new Result { ... }
},
ResultSet 2 = ...
};
although this gets pretty nasty, and could make it hard to debug down the road. What about a constructor that took the node and parsed it out?
Upvotes: 1
Reputation: 134491
Assuming the properties are accessible, you can simply set the properties through the regular object initializer syntax. Just add a pair of braces after your new
call and set the properties.
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. */,
};
Upvotes: 3