這裏是產生你想要的結果
它的核心的例子是這樣的:
- 組中的元素可以通過
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();
}
}
那麼你到目前爲止嘗試過什麼? – Deeko
尋找LINQ +支點並找出沒有銀彈。之前已經有很多方面提出過這個問題。 –