62,046
社区成员
发帖
与我相关
我的任务
分享
public class City
{
public string Name { get; set; }
public int CID { get; set; }
public int PID { get; set; }
public int Score { get; set; }
}
public static void GetAll(IEnumerable<City> list, int PID, Dictionary<int, int> d, Dictionary<int, int> count)
{
IEnumerable<City> l = list.Where(x => x.PID == PID);
foreach (City c in l)
{
if (c.PID == 0)
{
d.Add(c.CID, c.Score);
count.Add(c.CID, 1);
}
else
{
if (!d.ContainsKey(c.PID))
{
int resultID = -1;
GetParent(list, c.PID, ref resultID);
if (resultID != -1)
{
d[resultID] += c.Score;
count[resultID] += 1;
}
}
else
{
d[c.PID] += c.Score;
count[c.PID] += 1;
}
}
GetAll(list, c.CID, d, count);
}
}
public static void GetParent(IEnumerable<City> ie, int PID, ref int ResultID)
{
City c = ie.Where(x => x.CID == PID).First();
if (c != null)
{
if (c.PID == 0)
ResultID = c.CID;
else
GetParent(ie, c.PID, ref ResultID);
}
}
static void Main(string[] args)
{
List<City> list = new List<City>(){
new City(){Name="中国",CID=1,PID=0,Score=1},new City(){Name="上海",CID=2,PID=1,Score=2},new City(){Name="北京",CID=3,PID=1,Score=3},
new City(){Name="徐汇",CID=8,PID=2,Score=8},new City(){Name="莲花路",CID=9,PID=8,Score=11},
new City(){Name="小日本",CID=4,PID=0,Score=4},new City(){Name="东京",CID=5,PID=4,Score=5},
new City(){Name="东京塔",CID=10,PID=5,Score=10},
new City(){Name="美国",CID=6,PID=0,Score=6},new City(){Name="纽约",CID=7,PID=6,Score=7},
new City(){Name="中央公园",CID=11,PID=7,Score=11}};
Dictionary<int, int> dic = new Dictionary<int, int>();
Dictionary<int, int> count = new Dictionary<int, int>();
GetAll(list, 0, dic, count);
foreach (KeyValuePair<int, int> k in dic)
{
Console.WriteLine("CID:{0} 得分:{1} 平均数:{2}", k.Key, k.Value, k.Value / count[k.Key]);
}
}
/*
CID:1 得分:25 平均数:5
CID:4 得分:19 平均数:6
CID:6 得分:24 平均数:8
*/