我有以下代码:
public class Show
{
public int Id { get; set; }
public decimal Revenue { get; set; }
public Movie Movie { get; set; }
public Theater Theater { get; set; }
public City City { get; set; }
public DateTime ShownAt { get; set; }
}
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Theater
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
我们假设我将使用以下代码获得以下输出:
IEnumerable<Show> shows = GetShows();
var result = shows.Select(x => new { Movie = x.Movie.Name, Theater = x.Theater.Name, City = x.City.Name, x.ShownAt.ToString(), x.Revenue });
结果
Movie, Theater, City, ShownAt, Revenue
------------------------------------------------------
Movie1, Theater1, Boston, 2011-11-01 11:00:00.000, 100
Movie2, Theater1, Boston, 2011-11-01 12:00:00.000, 125
Movie1, Theater1, Boston, 2011-11-02 11:00:00.000, 110
Movie2, Theater2, New York, 2011-11-02 12:00:00.000, 125
到目前为止一切顺利。
我正在寻找的输出我可以使用以下代码获得:
var showResult = shows.GroupBy(x => new { Movie = x.Movie.Name, Theater = x.Theater.Name, City = x.City.Name }).Select(x => new { x.Key.Movie, x.Key.Theater, x.Key.City, Revenue = x.Sum(y => y.Revenue) });
结果
Movie, Theater, City, Revenue
-----------------------------------------------
Movie1, Theater1, Boston, 210
Movie2, Theater1, Boston, 125
Movie2, Theater2, New York, 125
但我还想包括第五个名为revenueKey的专栏。我会通过将Theater和City的第一个结果组分组并将其除以行数来获得此值。
所以,波士顿剧院1的收入关键是(100 + 125 + 110)/ 3 = 111.66,纽约剧院2的收入关键是(125)/ 1 = 125.在代码中它看起来像: / p>
var revenueKeys = shows.GroupBy(x => new { Theater = x.Theater.Name, City = x.City.Name }).Select(x => new { x.Key.Theater, x.Key.City, Revenue = x.Sum(y => y.Revenue), RevenueKey = x.Sum(y => y.Revenue) / x.Count() });
我有没有办法结合showResult和revenueKey LINQ查询来获得以下结果?
Movie, Theater, City, Revenue, RevenueKey
-----------------------------------------------
Movie1, Theater1, Boston, 210, 111.66
Movie2, Theater1, Boston, 125, 111.66
Movie2, Theater2, New York, 125, 125