1 回答
TA贡献1827条经验 获得超8个赞
您想要Count()该Quality属性,因此将其用作分组中的键确实有意义。如果您只是省略它并仅按年份和位置分组,您将获得所需的输出。
public class Program
{
public static void Main()
{
var fruits = new List<Fruit> {
new Fruit { Id = 1, Name = "Apple", Year = "year1", Quality = "Good", Location ="Asia"},
new Fruit { Id = 2, Name = "Apple", Year = "year2", Quality = "Better", Location ="Asia"},
new Fruit { Id = 3, Name = "Apple", Year = "year3", Quality = "Better", Location ="Asia"},
new Fruit { Id = 4, Name = "Apple", Year = "year1", Quality = "Best", Location ="Africa"},
new Fruit { Id = 5, Name = "Orange", Year = "year1", Quality = "Vad", Location ="Asia"},
new Fruit { Id = 6, Name = "Orange", Year = "year2", Quality = "Better", Location ="Asia"},
new Fruit { Id = 7, Name = "Orange", Year = "year3", Quality = "Bad", Location ="Asia"},
};
var result = fruits.GroupBy(f => new { f.Year,f.Location})
.Select(g => new
{
Year = g.Key.Year,
Location = g.Key.Location,
Good = g.Count(x => x.Quality == "Good"),
Better = g.Count(x => x.Quality == "Better"),
Best = g.Count(x => x.Quality == "Best"),
});
foreach(var line in result) {
Console.WriteLine(String.Format("Year: {0} - Location: {1} - Good: {2} - Better: {3} - Best: {4}", line.Year, line.Location, line.Good, line.Better, line.Best));
}
}
}
public class Fruit
{
public int Id { get; set; }
public string Name { get; set; }
public string Year { get; set; }
public string Quality { get; set; }
public string Location { get; set; }
}
输出:
Year: year1 - Location: Asia - Good: 1 - Better: 0 - Best: 0
Year: year2 - Location: Asia - Good: 0 - Better: 2 - Best: 0
Year: year3 - Location: Asia - Good: 0 - Better: 1 - Best: 0
Year: year1 - Location: Africa - Good: 0 - Better: 0 - Best: 1
小提琴:https ://dotnetfiddle.net/eg99at
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报