Reputation: 47995
This is my class, for example :
public class Point
{
public string Min { get; set; }
public string Max { get; set; }
public Point()
{
}
}
and I'm building dynamic objects through linq to xml :
var list = xDoc.Descendants("item").Select(item => new
{
NewPoint = new Point()
});
Now, I'd like to associate for each NewPoint
the value item.Min
and item.Max
.
Such as NewPoint.Min = item.Min
and NewPoint.Max = item.Max
, without creating a Class constructor with 2 param in the method.
Is it possible? Hope the question is clear...
Upvotes: 0
Views: 70
Reputation: 50164
You can use an object initializer:
Point = new Point() { Min = n["min"], Max = n["max"] }
(or however you get your values out of n
)
Alternatively, you can put a whole code block in your Select
:
.Select(n => {
var point = new Point();
point.Min = n["min"];
point.Max = n["max"];
return new { Point = point };
});
Also note: unless you're selecting other things as well, you don't need
n => new { Point = new Point() }
You can just use n => new Point()
and end up with an IEnumerable<Point>
rather than an IEnumerable<AnonymousClassContainingPoint>
.
Upvotes: 2
Reputation: 11955
I would just simplify the linq if you only want a list with Point
s:
var list = xDoc.Descendants("item").Select(item =>
new Point { Min = item.Min, Max = item.Max });
Upvotes: 0
Reputation: 11657
var list = xDoc.Descendants("item").Select(n => new
{
Point = new Point()
{
Min = n.Min,
Max = n.Max,
}
});
Upvotes: 1