这是一个产生您想要的结果的示例
它的核心是这样的:
Code
按属性对元素进行分组
Color
按属性对每个分组中的元素进行分组
- 处理每个分组,创建结果,其中每个
MonthX
属性设置为具有给定月份标识符的内部分组(按代码按颜色的项目)中的对象的计数
这专门处理问题中提供的 5 个月值,您可以将您喜欢的所有月份值拆分到结果对象上它们自己的属性中,或者如果需要其他值,则将其构建到月份索引与计数的字典中。
public enum Number
{
One = 11111,
Two = 22222,
Three = 33333,
Four = 44444,
Five = 55555
}
public class Data
{
public Number Code { get; set; }
public string CodeName { get { return Enum.GetName(typeof(Number), Code); } }
public ConsoleColor Color { get; set; }
public int Month { get; set; }
}
public class Result
{
public Number Code { get; set; }
public string CodeName { get { return Enum.GetName(typeof(Number), Code); } }
public ConsoleColor Color { get; set; }
public int Month1 { get; set; }
public int Month2 { get; set; }
public int Month3 { get; set; }
public int Month4 { get; set; }
public int Month5 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var items = new Data[]
{
new Data{Code = Number.One, Color = ConsoleColor.Red, Month = 1},
new Data{Code = Number.One, Color = ConsoleColor.Red, Month = 1},
new Data{Code = Number.One, Color = ConsoleColor.Red, Month = 2},
new Data{Code = Number.Two, Color = ConsoleColor.Green, Month = 2},
new Data{Code = Number.Three, Color = ConsoleColor.Yellow, Month = 3},
new Data{Code = Number.Four, Color = ConsoleColor.Blue, Month = 4},
new Data{Code = Number.Four, Color = ConsoleColor.Blue, Month = 4},
new Data{Code = Number.Five, Color = ConsoleColor.White, Month = 5},
};
var results = items.GroupBy(x => x.Code).Select(
x => x.GroupBy(y => y.Color)
.Select(z => new Result
{
Code = x.Key,
Color = z.Key,
Month1 = z.Count(q => q.Month == 1),
Month2 = z.Count(q => q.Month == 2),
Month3 = z.Count(q => q.Month == 3),
Month4 = z.Count(q => q.Month == 4),
Month5 = z.Count(q => q.Month == 5),
}).ToList());
var resultList = results.ToList();
}
}