我可以在Linq生成的传入新对象中使用get / set方法吗?

时间:2012-12-06 14:01:58

标签: c# linq class

这是我的班级,例如:

public class Point
{
    public string Min { get; set; }
    public string Max { get; set; }

    public Point()
    {

    }
}

我正在通过linq到xml构建动态对象:

var list = xDoc.Descendants("item").Select(item => new
{
    NewPoint = new Point()
});

现在,我想为每个NewPointitem.Minitem.Max关联。

例如NewPoint.Min = item.MinNewPoint.Max = item.Max,而不在方法中创建带有2个参数的类构造函数。

有可能吗?希望问题很明确......

3 个答案:

答案 0 :(得分:2)

您可以使用对象初始值设定项:

Point = new Point() { Min = n["min"], Max = n["max"] }

(或者你从n获得了你的价值)

或者,您可以在Select

中添加整个代码块
.Select(n => {
    var point = new Point();
    point.Min = n["min"];
    point.Max = n["max"];
    return new { Point = point };
});

另请注意:除非您选择其他内容,否则您不需要

n => new { Point = new Point() }

您可以使用n => new Point(),最后使用IEnumerable<Point>而不是IEnumerable<AnonymousClassContainingPoint>

答案 1 :(得分:1)

var list = xDoc.Descendants("item").Select(n => new
{
    Point = new Point()
    {
       Min = n.Min,
       Max = n.Max,
    }
});

答案 2 :(得分:0)

如果您只想要一个包含Point s的列表,我会简化linq:

var list = xDoc.Descendants("item").Select(item => 
    new Point { Min = item.Min, Max = item.Max });
相关问题