c# - C# 引用列表中的特定项目
问题描述
我创建了一类收藏品。该类包含一个字符串 Name、int Points 和 int Damage。我创建了一个名为“lifeforce”的 Collectable 实例,“Life Force”是名称,Points 的值设置为 1000。当实例化一个单独的不朽类时,我将一个 Collectable 实例添加到不朽的 List 中。如果我想查看不朽实例的生命力有多少点,我如何参考生命力点来获得价值?代码如下。
public class Collectable
{
public string Name { get; set; }
public int Points { get; set; }
public int Damage { get; set; }
public Collectable(string name, int points, int damage)
{
Name = name;
Points = points;
Damage = damage;
}
}
public class Immortal
{
public string Name { get; set; }
public string Origin { get; set; }
public string Superpower { get; set; }
public List<Collectable> Carrying { get; set; }
public string Saying { get; set; }
public string Bent { get; set; }
public Immortal(string name, string origin, string superpower, string saying, string bent, Collectable item)
{
Name = name;
Origin = origin;
Superpower = superpower;
Saying = saying;
Bent = bent;
this.Carrying = new List<Collectable>();
this.Carrying.Add(item);
}
public void Pickup(Collectable item)
{
this.Carrying.Add(item);
}
}
static void Main(string[] args)
{
Collectable lifeforce = new Collectable("Life Force", 1000, 0);
Collectable rubystone = new Collectable("Ruby Stone", 200, 0);
Collectable bagofdiamonds = new Collectable("Diamond Bag", 500, 0);
Immortal mighty = new Immortal("Mighty Man", "Mightopolis", "Might", "I am a mighty man!", "good",lifeforce);
foreach (var collecteditem in mighty.Carrying)
{
Console.WriteLine("Items in bag - " + collecteditem.Name);
}
var lifeforceIndx = 0;
lifeforceIndx = mighty.Carrying[0].Points
Console.WriteLine("Your Life Force is at " + mighty.Carrying[0].Points.ToString());
Console.ReadLine();
}
解决方案
你可以做 :
Console.WriteLine("Your Life Force is at " + mighty.Carrying.Where(x=>x.Name == "Life Force").Sum(x=>x.Points).ToString());
推荐阅读
- c - 如何在C中一次扫描多个字符?
- javascript - 当表单提交和刷新我的加载屏幕的页面再次出现时?
- rust - 如何在 NixOS 和 cargo 下安装具有 sqlite 支持的diesel-cli?
- javascript - API的“response.data”后如何获取数据
- python - 将两个熊猫数据框与一个公共列合并
- excel - 创建新工作表的子程序会在几分之一秒内打开 VBA 编辑器
- javascript - Bootstrap 5 - 调整窗口大小时的动画折叠动画
- javascript - 获取选定密码的 Firefox 扩展
- android - 使用http颤振发布数组
- parceljs - 你如何让包裹在我选择的特定浏览器中打开?