,c#,list,properties"/>

首页 > 解决方案 > 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();
    
    
            }

标签: c#listproperties

解决方案


你可以做 :

Console.WriteLine("Your Life Force is at " + mighty.Carrying.Where(x=>x.Name == "Life Force").Sum(x=>x.Points).ToString());
            

推荐阅读