[英]Using Linq to group a list of objects that contains primitives data into a new grouped list of objects
[英]Pass LINQ Group By Data Into New List Of Objects
我试图在C#中创建一个LINQ查询,它接受一个对象列表,执行一个分组并依赖列表,然后将结果传递给一个新的对象列表。
这是我的LINQ查询,它执行group by和count,但不将数据传输到我需要的列表中,而是传输匿名类型列表。
var dataPoints = from e in evaluations.Take(20)
group e.EvaluationID by e.description into g
select new { Profession = g.Key, Count = g.Count() };
dataPoints
变量返回匿名类型列表,数据类似于:
[0] Profession = "Doctor", Count = 12 [1] Profession = "Nurse", Count = 6 [2] Profession = "Health Visitor", Count = 2
我想返回一个DataPoint
对象列表,而不是将数据返回到匿名类型列表中。 下面是我的DataPoint
对象。
public class DataPoint
{
public DataPoint(double y, string label)
{
this.Y = y;
this.Label = label;
}
[DataMember(Name = "y")]
public Nullable<double> Y = null;
[DataMember(Name = "label")]
public string Label;
}
我已经尝试修改我的查询到这样的东西,但我得到一个错误,说DataPoint不包含一个带0参数的构造函数。
var dataPoints = from e in evaluations.Take(20)
group e.EvaluationID by e.description into g
select new DataPoint { Count = g.Count(), Profession = g.Key};
任何建议非常感谢。
要使属性初始值设定项起作用,您需要一个无参数构造函数,并且您的字段应该是可访问的属性:
public class DataPoint
{
[DataMember(Name = "y")]
public Nullable<double> Y { get; set; };
[DataMember(Name = "label")]
public string Label { get; set; }
public DataPoint()
{
}
public DataPoint(double y, string label)
{
Y = y;
Label = label;
}
}
现在你的代码应该编译,或者使用带有参数的构造函数作为评论中建议的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.