Mod*_*dro -1 c# arrays object visual-studio
我很难理解这一点.我做了一个瓶子对象,我有整个瓶子对象的重量.但我试图只指定一种"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;
}
Run Code Online (Sandbox Code Playgroud)
所以基本上,我只需要知道在碰到它们时如何只计算特定的对象,对吧?
如果您使用Linq,它只是一行代码.
public int findWeightByName(string name, Flaske[] kasse)
{
return kasse.Where(x => x.name == name).Sum(w => w.weight);
}
Run Code Online (Sandbox Code Playgroud)
Where使用传递的名称提取Flaske序列,Sum对序列进行处理以总结权重