Linq - 项目列表<a> to grouped List<b> with a C object within List<b>

时间:2016-04-03 23:15:15

标签: c# linq grouping

I have classes like:

public class A {
    public DateTime Date { get; set; }
    public int Hour { get; set; }
    public decimal Value { get; set; }
}

public class B {
    public DateTime Date { get; set; }
    public C C { get; set; }
}

public class C {
    public int Hour { get; set; }
    public decimal Value { get; set; }
}

I have a List<A> which contains a series of dates with hourly values for each. I'm trying to convert it from that format to that of type B, so a List<B>.

For instance, if there were 3 days' worth of data in the List<A> (i.e. 24 x 3 = 72 records), then there should be 3 objects of type B in the List<B> - one for each day with the 24 hours split up into the C type.

I know I can do it with nested foreach loops but I figured LINQ would be more elegant and would likely be better performance wise as well.

The code I'm trying is:

var res = from a in AList
          select (new List<B>
          {
              new B
              {
                  Date = a.Date,
                  C = new C() 
                  { 
                      Hour = a.Hour, 
                      Value = a.Value 
                  }
              }
          });

But it returns a list without the date grouping. I'm not sure how to establish that grouping. Would appreciate any help!

2 个答案:

答案 0 :(得分:2)

逻辑上,您的B类似乎应包含C个实例的集合

public class B {
    public DateTime Date { get; set; }
    public ICollection<C> C { get; set; }
}

因此,您可以使用group by填充这些实例:

var res = 
(
    from a in AList
    group a by a.Date into g
    select new B
    {
        Date = g.Key,
        C = 
        (
            from c in g
            select new C
            { 
                Hour = c.Hour, 
                Value = c.Value 
            }
        ).ToList()
    }
).ToList();

答案 1 :(得分:1)

        var newAList = from a in AList
                       select new B 
                       { 
                           Date = a.Date,
                           C = new C { Hour = a.Hour, Value = a.Value }
                       };

LINQ:优雅吗?是。但是比嵌套循环更好的性能?我不确定。