您可以使用嵌套的字典,所以很會照顧容易聚集的數據沒有太多的代碼,例如所以
static void Main(string[] args)
{
var data = new[]{
new { group="L1", date="2016-09-13", count=1},
new { group="L2", date="2016-09-13", count=2},
new { group="L3", date="2016-09-13", count=3},
new { group="L1", date="2016-09-12", count=1},
new { group="L2", date="2016-09-12", count=2},
new { group="L3", date="2016-09-12", count=3}
};
//convert data to dictionaries
var dictionaries = new Dictionary<string, Dictionary<string, int>>();
foreach (var row in data)
{
if (!dictionaries.ContainsKey(row.group))
dictionaries[row.group] = new Dictionary<string, int>();
if (!dictionaries[row.group].ContainsKey(row.date))
dictionaries[row.group][row.date] = row.count;
}
我認爲它已經非常容易使用和顯示,你可以使用字典獲取計數[「L1」] [「2016年9月13日」例如,如果你還想二維數組,轉換d的字典字典到二維數組使用一些for循環
//convert dictionary of dictionaries to 2D array
int groupNum = dictionaries.Keys.Count, dateNum = dictionaries.First().Value.Keys.Count;
string[,] array = new string[groupNum + 1, dateNum + 1];
array[0, 0] = "group";
//assign dates
for (int i = 1; i <= dateNum; i++)
array[0, i] = dictionaries.First().Value.Keys.ElementAt(i - 1);
//assign groups
for (int i = 1; i <= groupNum; i++)
array[i, 0] = dictionaries.Keys.ElementAt(i - 1);
//assign counts
for (int group = 1; group <= groupNum; group++)
for (int date = 1; date <= dateNum; date++)
{
array[group, date] = "0";
string groupName = array[group,0], dateString = array[0,date];
if(dictionaries[groupName].ContainsKey(dateString))
array[group, date] = dictionaries[groupName][dateString].ToString();
}
//print the 2D array
for (int row = 0; row < groupNum + 1; row++)
{
for (int column = 0; column < dateNum + 1; column++)
Console.Write("{0} ", array[row, column]);
Console.WriteLine();
}
Console.ReadLine();
}
什麼是錯誤,或不是預期的? – user5226582
這些組的「count」屬性是否相同?那麼'L1'中的所有條目都有一個數? – HimBromBeere
還有什麼'cd'和'list'在哪裏? –