我创建了一类收藏品。该类包含字符串Name、int Points和int Damage。我创建了一个名为";"生命力"生命力;是"名称","点"设置为值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());
查找所有名为"生命力;只需使用
Carrying.Where(collectable => string.Equals(collectable.Name, "Life Force", StringComparison.OrdinalIgnoreCase));
当Name属性具有不同拼写时,忽略大小写是必要的。
但我建议创建具有可收集类型的枚举,并在collectable类中使用此枚举。
例如
public class Collectable
{
public string Name { get; set; }
public int Points { get; set; }
public int Damage { get; set; }
public CollectableType Type { get; }
public Collectable(string name, int points,
int damage, CollectableType type)
{
Name = name;
Points = points;
Damage = damage;
Type = type;
}
}
找到所有Life Force收藏品,如下面的代码所示
Collectables.Where(collectable => collectable.Type == CollectableType.LifeForce);
如果你需要积分总和,而不仅仅是添加.Sum(collectable => collectable.Points)
来获得
Collectables.Where(collectable => collectable.Type == CollectableType.LifeForce)
.Sum(collectable => collectable.Points);
如果我做对了,那么这就是解决方案。