Reputation: 5105
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.
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.
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:
[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. Below is my DataPoint
object.
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.
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.
Upvotes: 3
Views: 507
Reputation: 62488
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.
Upvotes: 2