2013-01-19 2 views
8

나는 다음과 같은 클래스 구조가 있습니다Linq는 그룹 선택으로

: < PriceLog>은 내가 LINQ 쿼리는 다음과 같이 표현 된 데이터에 해당하는 출력을 생성하고자하는 목록

public class PriceLog 
{ 
    public DateTime LogDateTime {get; set;} 
    public int Price {get; set;} 
} 

LogDateTime | AVG (가격)
1 월 2012 | 2000
2 월 2012 | 3000

간단히 말해서 : 나는 연중 매월 평균 가격을 계산하고 싶습니다.
참고 : LogDateTime 속성은 내가 다음을 시도

LogDateTime.ToString("MMM yyyy")로 포맷하지만 원하는 결과가 생성됩니다 있는지 확실하지해야합니다

var result = from priceLog in PriceLogList 
         group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup 
         select new PriceLog { GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), SilverPrice = (int)dateGroup.Average(p => p.SilverPrice)}; 

답변

18

이렇게하면 날짜 문자열과 평균 가격이있는 두 속성이 포함 된 일련의 익명 개체가 제공됩니다 :

var query = from p in PriceLogList 
      group p by p.LogDateTime.ToString("MMM yyyy") into g 
      select new { 
       LogDate = g.Key, 
       AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
       AvgSilverPrice = (int)g.Average(x => x.SilverPrice) 
      }; 

당신은 PriceLog 객체의 목록을해야하는 경우 : 내 가격 필드 INT 및 평균 방법 복귀 .I이 도움이 될 희망을 두 배로 때문에 내가 int로 그것을 변환 한

var query = from p in PriceLogList 
      group p by p.LogDateTime.ToString("MMM yyyy") into g 
      select new PriceLog { 
       LogDateTime = DateTime.Parse(g.Key), 
       GoldPrice = (int)g.Average(x => x.GoldPrice), 
       SilverPrice = (int)g.Average(x => x.SilverPrice) 
      }; 
2
from p in PriceLog 
    group p by p.LogDateTime.ToString("MMM") into g 
    select new 
    { 
     LogDate = g.Key.ToString("MMM yyyy"), 
     GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
     SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    } 
+0

g.LogDateTime은 오류를 발생시킵니다! – Lucifer

+0

답변이 수정되었습니다. – MuhammadHani

2

당신은 이런 식으로 시도해야을 :

var result = 
     from priceLog in PriceLogList 
     group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup 
     select new { 
      LogDateTime = dateGroup.Key, 
      AvgPrice = dateGroup.Average(priceLog => priceLog.Price) 
     }; 
1
var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();