这是一个使用
Linq
的可能解决方案:
List<Item> items = new List<Item>
{
new Item { Name = "a", Value = 1, SubItems = new List<Item> { new Item { Name = "b", Value = 2, SubItems = new List<Item> { new Item { Name = "c", Value = 3, SubItems = null } } } } }
};
List<Item> items2 = new List<Item>
{
new Item { Name = "a", Value = 1, SubItems = new List<Item> { new Item { Name = "b", Value = 2, SubItems = new List<Item> { new Item { Name = "c", Value = 3, SubItems = null } } } } },
new Item { Name = "a", Value = 0, SubItems = new List<Item> { new Item { Name = "b", Value = 0, SubItems = new List<Item> { new Item { Name = "c", Value = 1, SubItems = null } } } } },
new Item { Name = "a", Value = 0, SubItems = new List<Item> { new Item { Name = "b", Value = 0, SubItems = new List<Item> { new Item { Name = "c", Value = 1, SubItems = new List<Item> { new Item { Name = "c", Value = 1, SubItems = null } } } } } } }
};
Item item = new Item { Name = "a", Value = 1, SubItems = new List<Item> { new Item { Name = "b", Value = 2, SubItems = new List<Item> { new Item { Name = "c", Value = 3, SubItems = null } } } } };
Console.WriteLine(SumItems(items));
Console.WriteLine(SumItems(items2));
Console.WriteLine(SumItem(item));
public class Item
{
public string Name { get; set; }
public int Value { get; set; }
public List<Item> SubItems { get; set; }
}
public int SumItems(List<Item> items)
{
int total = 0;
while(true)
{
if(items == null || items.Count < 1)
break;
total += items.Sum(b => b.Value);
items = items.SelectMany(a => a.SubItems ?? new List<Item>()).ToList() ?? new List<Item>();
}
return total;
}
public int SumItem(Item item)
{
int total = 0;
if(item == null)
return total;
if(item.SubItems == null || item.SubItems.Count < 1)
return item.Value;
total += item.Value;
total += SumItems(item.SubItems);
return total;
}