我很难理解这一点。我做了一个瓶子对象,我有整个瓶子对象的重量。但我试图只指定一种“Cola Cola”瓶子。但是,我知道如何查看我制作的清单并计算总重量。但如果我只想算“可口可乐”的物品,我就迷路了。有什么帮助吗?
class Flaske
{
public String name = "Coca Cola";
public int weight = 14;
public Bottles(String na, int ve)
{
name = na;
weight = ve;
}
}
//Total Bottle Weight
public int findCocaColaWeight(Flaske[] kasse)
{
int result = 0;
int i = 0;
while (i < kasse.Length)
{
if (kasse[i] != null)
{
result = result + kasse[i].Weight.Equals("Coca Cola");
}
i = i + 1;
}
return result;
}
//Find Coca Cola Weight
public int findCocaColaWeight(Flaske[] kasse)
{
int result = 0;
int i = 0;
while (i < kasse.Length)
{
if (kasse[i] != null)
{
result = result + kasse[i].Weight;
}
i = i + 1;
}
return result;
}
所以基本上,我只需要知道在遇到特定对象时如何计算它们,对吧?
答案 0 :(得分:7)
如果您使用Linq,只需一行代码。
public int findWeightByName(string name, Flaske[] kasse)
{
return kasse.Where(x => x.name == name).Sum(w => w.weight);
}
Where使用传递的名称提取Flaske序列,Sum对序列进行处理以总结权重
答案 1 :(得分:0)
根据评论,我假设您的代码应如下所示:
//Total Bottle Weight
public int findTotalWeight(Flaske[] kasse)
{
int result = 0;
int i = 0;
while (i < kasse.Length)
{
if (kasse[i] != null)
result = result + kasse[i].weight;
i = i + 1;
}
return result;
}
//Find Coca Cola Weight
public int findCocaColaWeight(Flaske[] kasse)
{
int result = 0;
int i = 0;
while (i < kasse.Length)
{
if (kasse[i] != null && kasse[i].name.Equals("Coca Cola"))
result = result + kasse[i].weight;
i = i + 1;
}
return result;
}