gpt4 book ai didi

c# - 将 LINQ Group By 数据传递到新的对象列表中

转载 作者:行者123 更新时间:2023-11-30 16:41:13 25 4
gpt4 key购买 nike

我正在尝试在 C# 中创建一个 LINQ 查询,它获取一个对象列表,对列表执行分组和计数,然后将结果传递到一个新的对象列表中。

这是我目前的 LINQ 查询,它执行分组依据和计数,但没有将数据传输到我需要的列表中,而是一个匿名类型列表。

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;
}
}

现在您的代码应该可以编译,或者像评论中建议的那样使用带参数的构造函数。

关于c# - 将 LINQ Group By 数据传递到新的对象列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49729122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com