C#/.NET求助

来源:百度知道 编辑:UC知道 时间:2024/06/18 01:49:23
List<product>集合中有N个元素,元素属性有NAME和COUNT,
现向集合中添加元素,遍历集合,若有NAME属性相同则COUNT+1,
若不存在则添加新元素

product 是一个类吧,先写好他的2个属性:
class Product
{
public string Name { get; set; }
public int Count { get; set; }
}
添加新元素的方法:
private List<Product> AddList(List<Product> list, string name, int count)
{
bool has = false;
foreach (Product pro in list)
{
if (pro.Name.Equals(name))
{
pro.Count += 1;
has = true;
break;
}
}
if (!has)
{
Product p = new Product();
p.Name = name;
p.Count = count;
list.Add(p);
}
return list;
}