强类型List.GroupBy()

Chr*_*ath 1 c# linq group-by

我一直试图在谷歌和SO上找到答案

但我发现的所有地方都使用匿名类型的结果列表

我想要实现的是采取一个 List<SecondaryStandard>

并创建一个分组列表 SecondaryStandard

每个都SecondaryStandard看起来像这样

public class SecondaryStandard
{

    public string Id { get; set; }
    public int IdNumeric { get; set; }
    public string IdText { get; set; }
    public Sample Sample { get; set; }
    public string StandardName { get; set; }
    public DateTime DateCompleted { get; set; }
    public SamplePoint SamplingPoint{ get; set; }
    public Instrument Instrument{ get; set; }
    public string ContainerId { get; set; }
    public double Value { get; set; }
    public string ComponentName { get; set; }
    public string PointLocation { get; set; }
    public string Description { get; set; }
    public string Description2 { get; set; }
    public string Analysis { get; set; }
    public string Units { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我想要的是一个List(),其中Value属性是每个ComponentName的平均结果.

关于如何以强类型方式实现这一点的任何想法,还是我需要吸收它并使用匿名对象来实现我正在寻找的东西?

Tom*_*ski 5

你是这个意思?

List<SecondaryStandard> list = new List<SecondaryStandard>();
// populate list

List<SecondaryStandard> result = list
    .GroupBy(l => l.ComponentName)
    .Select(s => new SecondaryStandard() { ComponentName = s.Key, Value = s.Average(x => x.Value) }).ToList();
Run Code Online (Sandbox Code Playgroud)