简体   繁体   English

将LINQ Group By Data传递给新的对象列表

[英]Pass LINQ Group By Data Into New List Of Objects

I am trying to create a LINQ query in C# which takes a list of objects, performs a group by and count on the list, and then passes the results into a new list of objects. 我试图在C#中创建一个LINQ查询,它接受一个对象列表,执行一个分组并依赖列表,然后将结果传递给一个新的对象列表。

This is my LINQ query at the moment which performs the group by and count, but not transferring the data into the list I need, instead a list of anonymous types. 这是我的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() };

The dataPoints variable returns a list of anonymous types and the data looks something like: dataPoints变量返回匿名类型列表,数据类似于:

 [0] Profession = "Doctor", Count = 12 [1] Profession = "Nurse", Count = 6 [2] Profession = "Health Visitor", Count = 2 

Rather than return the data into a list of anonymous types, I'd like to return a list of DataPoint objects. 我想返回一个DataPoint对象列表,而不是将数据返回到匿名类型列表中。 Below is my DataPoint object. 下面是我的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;
}

I've tried amending my query to something like this, but I get an error saying DataPoint does not contain a constructor taking 0 arguments. 我已经尝试修改我的查询到这样的东西,但我得到一个错误,说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};

Any suggestions much appreciated. 任何建议非常感谢。

For the property initializer to work you need a parameterless constructor and your fields should be properties to be accessible: 要使属性初始值设定项起作用,您需要一个无参数构造函数,并且您的字段应该是可访问的属性:

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

and now your code should compile, alternatively use the constructor with parameters as someone suggested in comments. 现在你的代码应该编译,或者使用带有参数的构造函数作为评论中建议的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM