C# 枚举和集合练习

帮助一家餐馆

Lumberjack.cs类:

    enum Flapjack
    {
        Crispy,
        Soggy,
        Browned,
        Banana,
    }

    internal class Lumberjack
    {
        public string Name { get; private set; }
        private Stack<Flapjack> flapjackStack = new Stack<Flapjack>();//初始化为一个空栈

        /// 
        /// 使用构造器设置属性
        /// 
        /// 
        public Lumberjack(string name)
        {
            Name = name;
        }
        
        /// 
        /// 将一个煎饼压入栈
        /// 
        /// 
        public void TakeFlapjack(Flapjack flapjack) 
        {
            flapjackStack.Push(flapjack);
        }

        public void EatFlapjacks()
        {
            Console.WriteLine($"{Name} is eating flapjacks");
            while (flapjackStack.Count > 0)
            {
                Console.WriteLine(
                    $"{Name} ate a {flapjackStack.Pop().ToString().ToLower()} flapjack");
            }
        }
    }

Main方法:

        static void Main(string[] args)
        {
            Random random = new Random();
            Queue<Lumberjack> lumberjacks = new Queue<Lumberjack>();

            string name;
            Console.WriteLine("First lumberjack's name: ");
            while ((name = Console.ReadLine()) != "") 
            {
                Console.Write("Number of flapjacks: ");
                if (int.TryParse(Console.ReadLine(), out int number))
                {
                    Lumberjack lumberjack = new Lumberjack(name);
                    for (int i = 0; i < number; i++)
                    {
                        lumberjack.TakeFlapjack((Flapjack)random.Next(0,4));//创建各个Lumerjack对象,调用它的TakeFlapjack方法并提供一个随机的煎饼。然后将这个引用入队。
                    }
                    lumberjacks.Enqueue(lumberjack);
                }
                Console.Write("Next lumberjack's name (blank to end): ");
            }

            while (lumberjacks.Count > 0)
            {
                Lumberjack next = lumberjacks.Dequeue();
                next.EatFlapjacks();
            }//用户增加完伐木工后,Main方法使用一个while循环将各个Lumberjack引用出队,并调用它的EatFlapjacks方法
        }

扑克牌列表

Card.cs类:

    internal class Card
    {
        public Values Value { get; private set; }
        public Suits  Suit { get; private set; }

        public Card( Values value, Suits suit) 
        {
            this.Value = value;
            this.Suit = suit;
        }

        public string Name
        {
            get 
            {
                return $"{Value} of {Suit}"; 
            }
        }

        public override string ToString()
        {
            return Name;
        }
    }

Suits集合:

    enum Suits
    {
        Diamonds,
        Clubs,
        Hearts,
        Spades,
    }

Values集合:

    enum Values
    {
        Ace = 1,
        Two = 2,
        Three = 3,
        Four = 4,
        Five = 5,
        Six = 6,
        Seven = 7,
        Eight = 8,
        Nine = 9,
        Ten = 10,
        Jack = 11,
        Queen = 12,
        King = 13,
    }

CardComparerByValue.cs

    internal class CardComparerByValue : IComparer<Card>
    {
        public int Compare(Card? x, Card? y)
        {
            if (x is null && y is null)
            {
                return 0;
            }

            if (x is null)
            {
                return -1;
            }

            if (y is null)
            {
                return 1;
            }

            if (x.Suit != y.Suit)
            {
                return x.Suit < y.Suit ? -1 : 1;
            }

            return x.Value < y.Value ? -1 : x.Value > y.Value ? 1 : 0;
        }
    }

Main方法:

    internal class Program
    {
        private static readonly Random random = new Random();
        static void Main(string[] args)
        {
            List<Card> cards = new List<Card>();
            Console.Write("Enter number of cards: ");
            if (int.TryParse(Console.ReadLine(), out int numberOfCards))
                for (int i = 0; i < numberOfCards; i++)
                    cards.Add(RandomCard());
            PrintCards(cards);

            cards.Sort(new CardComparerByValue());
            Console.WriteLine("\n... sorting the cards ...\n");

            PrintCards(cards);


        }

        static Card RandomCard()
        {
            return new Card((Values)random.Next(1,14),(Suits)random.Next(4));
        }

        static void PrintCards(List<Card> cards)
        {
            //foreach (Card card in cards) 
            //{
            //    Console.WriteLine(card.Name);
            //}


        }
    }

字典简单使用

RetiredPlayer.cs类:

    /// 
    /// 退役棒球队队员类
    /// 
    internal class RetiredPlayer
    {
        public string Name { get; private set; }
        public int YearRetired { get; private set; }

        public RetiredPlayer(string player, int yearRetired)
        {
            Name = player;
            YearRetired = yearRetired;
        }
    }

Main方法:

        static void Main(string[] args)
        {
            
            Dictionary<int, RetiredPlayer> retiredYankees = new Dictionary<int, RetiredPlayer>()
            {
                {3, new RetiredPlayer("Babe Ruth",1948) },
                {4, new RetiredPlayer("Lou Gehrig",1939) },
                {5, new RetiredPlayer("Joe DiMaggio",1952) },
                {7, new RetiredPlayer("Mickey Mantle",1969) },
                {8, new RetiredPlayer("Yogi Berra",1972) },
                {10, new RetiredPlayer("Phil Rizzuto",1985) },
                {23, new RetiredPlayer("Don Mattingly",1997) },
                {42, new RetiredPlayer("Jackie Robinson",1993) },
                {44, new RetiredPlayer("Reggie Jackson",1993) },
            };//使用一个集合初始化器在Dictionary中填充RetiredPlayer对象

            foreach (int jerseyNumber in retiredYankees.Keys)
            {
                RetiredPlayer player = retiredYankees[jerseyNumber];
                Console.WriteLine($"{player.Name} #{jerseyNumber} retired in {player.YearRetired}");
            }//使用foreach循环迭代处理键,并为集合中每个退役的球员写一行输出
        }

队列是FIFO_先进先出

        static void Main(string[] args)
        {
            //创建队列并添加四个元素
            Queue<string> myQueue = new Queue<string>();
            myQueue.Enqueue("first in line");
            myQueue.Enqueue("second in line");
            myQueue.Enqueue("third in line");
            myQueue.Enqueue("last in line");

            //Peek“查看”栈中的第一项而不删除它
            Console.WriteLine($"Peek() returned:\n{myQueue.Peek()}");//①

            //Pop 从栈底取出下一项
            Console.WriteLine($"The first Dequeue() returned:\n{myQueue.Dequeue()}");//②
            Console.WriteLine($"The second Dequeue() returned:\n{myQueue.Dequeue()}");//③

            //清除从队列中删除所有项目
            Console.WriteLine($"Count before Clear():\n{myQueue.Count}");//④
            myQueue.Clear();
            Console.WriteLine($"Count after Clear():\n{myQueue.Count}");//⑤
        }

栈是LIFI_后进先出

        static void Main(string[] args)
        {
            //创建栈并添加四个元素
            Stack<string> myStack = new Stack<string>();
            myStack.Push("first in line");
            myStack.Push("second in line");
            myStack.Push("third in line");
            myStack.Push("last in line");

            //Peek“查看”队列中的第一项而不删除它
            Console.WriteLine($"Peek() returned:\n{myStack.Peek()}");//①

            //Dequeue 从队列的 FRONT 中提取下一个元素
            Console.WriteLine($"The first Dequeue() returned:\n{myStack.Pop()}");//②
            Console.WriteLine($"The second Dequeue() returned:\n{myStack.Pop()}");//③

            //清除从队列中删除所有项目
            Console.WriteLine($"Count before Clear():\n{myStack.Count}");//④
            myStack.Clear();
            Console.WriteLine($"Count after Clear():\n{myStack.Count}");//⑤
        }

Test列表

Breeds.cs:

    enum Breeds
    {
        Collie = 3,
        Corgi = -9,
        Dachshund = 7,
        Pug = 0,
    }

Dog.cs:

    internal class Dog : IComparable<Dog>
    {
        public Breeds Breed { get; set; }
        public string Name { get; set; }
        public int CompareTo(Dog other)
        {
            if(Breed > other.Breed) return -1;
            if(Breed < other.Breed) return 1;
            return -Name.CompareTo(other.Name);
        }

        public override string ToString() 
        {
            return $"A {Breed} named {Name}";
        }
    }

Main方法:

        static void Main(string[] args)
        {
            List<Dog> dogs = new List<Dog>()
            {
                new Dog(){ Breed = Breeds.Dachshund,Name = "Franz" },
                new Dog(){ Breed = Breeds.Collie,Name = "Petunia" },
                new Dog(){ Breed = Breeds.Pug,Name = "Porkchop" },
                new Dog(){ Breed = Breeds.Dachshund,Name = "Brunhilda" },
                new Dog(){ Breed = Breeds.Collie,Name = "Zippy" },
                new Dog(){ Breed = Breeds.Corgi,Name = "Carrie" },
            };
            dogs.Sort();
            foreach (Dog dog in dogs) 
            {
                Console.WriteLine(dog);
            }
        }

鸭子列表

Duck.cs类:

    internal class Duck : IComparable<Duck>//让这个类实现IComparable接口时,要指定所比较的类型
    {
        public int Size 
        {
            get; set;
        }

        public KindOfDuck Kind { get; set; }

        /// 
        /// 重写ToString方法在IDE中查看你的Duck
        /// 
        /// 
        public override string ToString()
        {
            return $"A {Size} inch {Kind}";
        }
        public int CompareTo(Duck? duckToCompare)
        {
            // 比较逻辑实现
            // 返回负数、零或正数,表示当前对象小于、等于或大于要比较的对象
            // 可以根据自己的需求来实现具体的比较逻辑
            // 例如,比较大小或种类等属性

            if (duckToCompare == null)
            {
                // 处理 duckToCompare 为 null 的情况
                // 可根据业务需求来确定返回值
                return 1; // 假设当前对象大于 null 对象
            }

            // 比较逻辑
            // 根据实际需要来确定比较的属性和逻辑
            if (Size < duckToCompare.Size)
            {
                return -1;
            }
            else if (Size > duckToCompare.Size)
            {
                return 1;
            }
            else
            {
                // 大小相等时,可以根据种类进行比较
                return Kind.CompareTo(duckToCompare.Kind);
            }
        }
    }

    enum KindOfDuck 
    {
        Mallard,
        Muscovy,
        Loon,
    }

DuckComparer.cs

    enum SortCriteria
    {
        SizeThenKind,
        KindThenSize,
    }
    internal class DuckComparer : IComparer<Duck>
    {
        public SortCriteria SortBy = SortCriteria.SizeThenKind;

        public int Compare(Duck ? x, Duck ? y)
        {
            if (x is null || y is null)
                return 0;
            // 根据排序标准进行比较
            if (SortBy == SortCriteria.SizeThenKind)
            {
                // 先按照大小比较
                if (x.Size > y.Size)
                    return 1;
                else if (x.Size < y.Size)
                    return -1;
                else
                    return 0;
            }
            else
            {
                // 先按照种类比较
                if (x.Kind > y.Kind)
                    return 1;
                else if (x.Kind < y.Kind)
                    return -1;
                else
                {
                    // 如果种类相同,则按照大小比较
                    if (x.Size > y.Size)
                        return 1;
                    else if (x.Size < y.Size)
                        return -1;
                    else
                        return 0;
                }
            }
        }

    }

DuckComparerByKind.cs

    internal class DuckComparerByKind : IComparer<Duck>
    {
        public int Compare(Duck? x, Duck? y)
        {
            // 检查其中一个对象是否为null,如果是,则视为相等,返回0
            if (x == null || y == null)
                return 0;
            else if (x == null)
                return -1;
            else if (y == null)
                return 1;

            // 比较鸭子的种类属性
            if (x.Kind < y.Kind)
                return -1;  // x的种类小于y的种类,x排在y之前
            else if (x.Kind > y.Kind)
                return 1;   // x的种类大于y的种类,x排在y之后
            else
                return 0;   // 种类相同,视为相等
        }

    }

DuckComparerBySize.cs

    /// 
    /// 比较器对象是实现了IComparer的一个类的实例,可以作为参数传递到List。
    /// 
    class DuckComparerBySize : IComparer<Duck>
    {
        //public int Compare(Duck x, Duck y)
        //{
        //    if(x.Size < y.Size)
        //        return -1;
        //    if(x.Size > y.Size)//如果Compare返回一个负数,这说明对象x应当在对象y前面,也就是x "小于" y。
        //        return 1;
        //    return 0;           //正值表示对象x应当在对象y后面。x "大于" y。 0表示它们是"相等的"。
        //}

        public int Compare(Duck? x, Duck? y)
        {
            // 比较逻辑实现
            // 返回负数、零或正数,表示 x 小于、等于或大于 y
            // 可根据自己的需求来实现具体的比较逻辑

            if (x == null && y == null)
            {
                return 0; // x 和 y 都为 null,则视为相等
            }
            else if (x == null)
            {
                return -1; // x 为 null,y 不为 null,则视为 x 小于 y
            }
            else if (y == null)
            {
                return 1; // y 为 null,x 不为 null,则视为 x 大于 y
            }

            // x 和 y 都不为 null,进行实际的比较逻辑
            if (x.Size < y.Size)
            {
                return -1;
            }
            else if (x.Size > y.Size)
            {
                return 1;
            }
            else
            {
                return 0; // 大小相等,视为相等
            }
        }

    }

Program.cs

    internal class Program
    {
        static void Main(string[] args)
        {
            List<Duck> ducks = new List<Duck>()
            {
                new Duck(){ Kind = KindOfDuck.Mallard, Size = 17},
                new Duck(){ Kind = KindOfDuck.Muscovy, Size = 18},
                new Duck(){ Kind = KindOfDuck.Loon, Size = 14},
                new Duck(){ Kind = KindOfDuck.Muscovy, Size = 11},
                new Duck(){ Kind = KindOfDuck.Mallard, Size = 14},
                new Duck(){ Kind = KindOfDuck.Loon, Size = 13},
            };//集合初始化器可以让代码更简洁
            ducks.GetEnumerator();
            //ducks.Sort();

            //IComparer sizeComparer = new DuckComparerBySize();
            //ducks.Sort(sizeComparer);

            //IComparer kindComparer = new DuckComparerByKind();
            //ducks.Sort(kindComparer);

            DuckComparer comparer = new DuckComparer();
            Console.WriteLine("\nSorting by kind then size\n");
            comparer.SortBy = SortCriteria.KindThenSize;
            ducks.Sort(comparer);
            PrintDucks(ducks);

            Console.WriteLine("\nSorting by size then kind\n");
            comparer.SortBy = SortCriteria.SizeThenKind;
            ducks.Sort(comparer);
            PrintDucks(ducks);

            Console.WriteLine(new Duck().ToString());

        }

        public static void PrintDucks(List<Duck> ducks)
        {
            //foreach (Duck duck in ducks)
            //{
            //    Console.WriteLine($"{duck.Size} inch {duck.Kind}");
            //}

            foreach (Duck duck in ducks)
            {
                Console.WriteLine(duck);
            }
        }
    }

Test字典

    internal class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string,string> favoriteFoods = new Dictionary<string,string>();
            //为这个字典增加4个键值对,键是人名,值是那个人喜欢的食物
            favoriteFoods["Alex"] = "hot dogs";
            favoriteFoods["A'ja"] = "pizza";
            favoriteFoods["Jules"] = "falafel";
            favoriteFoods["Naima"] = "spaghetti";
            string name;
            while ((name = Console.ReadLine()) != "")
            {
                if (favoriteFoods.ContainsKey(name))
                    Console.WriteLine($"{name}'s favorite food is {favoriteFoods[name]}");//{favoriteFoods[name]} 要这样得到一个对应键的值
                else
                    Console.WriteLine($"I don't know {name}'s favorite food");
            }
        }
        /****
         * Diction功能:
         * 1.增加一项
         *可以使用字典的索引器用中括号向字典增加一项:
         *Dictionary myDictionary = new Doctionary();
         *myDictionary["some key"] = "some value";
         *还可以使用字典的Add方法增加一项:
         *Dictionary myDictionary = new Dictionary();
         *myDictionary.Add("some key","some value");
         *2.使用健查找一个值
         *使用字典最重要的工作就是用索引器查找值,把值存储在字典中就是为了能使用唯一的健来查找这些值,而且这个字典会返回一个字符串值:
         *string lookValues = myDictionary["some key"];
         *3.删除一项
         *与列表一样,可以使用Remove方法从一个字典删除一项。只需要向Remove方法传递健,就能将键和值都删除:
         *myDictionary.Remove("some key");
         *注:字典中的键是唯一的;任何键都只会出现一次。值可以出现任意多次,两个键可以有相同的值。这样查询或删除一个键时,字典就会知道要删除哪一个
         *4.得到键列表
         *可以使用字典的keys属性得到字典中所有键的一个列表,并使用一个foreach循环迭代处理这个列表:
         *foreach(string key in myDictionary.Keys){ ... };//Keys是Dictionary对象的一个属性。这个特定的字典中包含字符串键,所以Keys是一个字符串集合。
         *5.统计字典中的键值对个数
         *Count属性会返回字典中的键/值对个数:
         *int howMany = myDictionary.Count;
         *6.键和值可以是不同的类型
         *字典能存储任何类型,不只是值类型(为对象指定唯一的ID号时,通常会看到将整数映射到对象的字典),还可以是任何对象
         *例:存储一个整数作为键,并存储一个Duck对象引用作为值:
         *Dictionary duckIds = new Dictionary();
         *duckIds.Add(376,new Duck(){Kind = KindOfDuck.Mallard,Size = 15});
         * ****/
    }

Test

        static void Main(string[] args)
        {
            Stack<string> myStack = new Stack<string>();
            myStack.Push("first in line");
            myStack.Push("second in line");
            myStack.Push("third in line");
            myStack.Push("last in line");

            Queue<string> myQueue = new Queue<string>(myStack);//将栈转换为队列
            List<string> myList = new List<string>(myStack);//将队列赋值到列表
            Stack<string> anotherStack = new Stack<string>(myStack);//把列表复制到另一个栈

            Console.WriteLine(
                $@"myQueue has {myQueue.Count} items  myList has {myList.Count} items anotherStack has {anotherStack.Count} items");
        }

你可能感兴趣的:(c#,开发语言,visualstudio)