首页 > 解决方案 > C# 无法从值(字符串 [])中获取字典键(字符串)

问题描述

我正在尝试创建一个程序,在 C# 中对动物进行分类,您可以在其中指定动物的王国、门、类、目、科、属和种,然后程序输出它是什么动物。

我正在使用字典来表示所有动物string animalType, string[] animalAttributes

为了让它工作,我需要能够找到给定值的字典键,我为此创建了一个方法,但我不断收到索引错误。

我已经浏览了一些帖子,但不幸的是,我找不到任何解决此问题的方法。

在此先感谢您的帮助!

我的代码

动物.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Challenge_4___Classification
{
    class Animal
    {
        /* Propeties */

        public string AnimalType { get; private set; } = "none";
        private static Dictionary<string, string[]> AnimalDictionary { get; set; } = new Dictionary<string, string[]>();
        public string Kingdom { get; set; }
        public string Phylum { get; set; }
        public string Class { get; set; }
        public string Order { get; set; }
        public string Family { get; set; }
        public string Genus { get; set; }
        public string Species { get; set; }
        public string[] AnimalAttributes { get; set; } = new string[7];

        /****************************************************************************************/

        /* Constructors */

        public Animal(string kingdom, string phylum, string _class, string order, string family, string genus, string species )
        {
            Kingdom = kingdom;
            Phylum = phylum;
            Class = _class;
            Order = order;
            Family = family;
            Genus = genus;
            Species = species;

            SetAnimalAttirbutes();
            AddDomesticAnimals();
        }

        /****************************************************************************************/

        /* Methods */

        public void SetAnimalAttirbutes()
        {
            AnimalAttributes[0] = Kingdom;
            AnimalAttributes[1] = Phylum;
            AnimalAttributes[2] = Class;
            AnimalAttributes[3] = Order;
            AnimalAttributes[4] = Family;
            AnimalAttributes[5] = Genus;
            AnimalAttributes[6] = Species;
        }

        private void AddDomesticAnimals()
        {
            AnimalDictionary.Add("horse", new string[7] { "animalia", "chordata" , "mammalia", "perissodactyla", "equidae", "equus", "ferus" } );
            AnimalDictionary.Add("cow", new string[7] { "animalia", "chordata", "mammalia", "artiodactyla", "bovidae", "bos", "taurus" } );
            AnimalDictionary.Add("sheep", new string[7] { "animallia", "chordata", "mammalia", "artiodactyla", "bovidae", "ovis", "aries" } );
            AnimalDictionary.Add("pig", new string[7] { "animalia", "chordata", "mammalia", "artiodactyla", "suidae", "sus", "scrofa" } );
            AnimalDictionary.Add("dog", new string[7] { "animalia", "chordata", "mammalia", "carnivora", "canidae", "canis", "lupus" } );
            AnimalDictionary.Add("cat", new string[7] { "animalia", "chordata", "mammalia", "carnivora", "felidae", "felis", "silvestris" } );
            AnimalDictionary.Add("lion", new string[7] { "animalia", "chordata", "mammalia", "carnivora", "felidae", "panthera", "leo" } );
            AnimalDictionary.Add("tiger", new string[7] { "animalia", "chordata", "mammalia", "carnivora", "felidae", "panthera", "tigris" });
            /*AnimalDictionary.Add("dolphin", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("seal", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("penguin", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("ostrich", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("sparrow", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("spider", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("ant", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("bee", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("wasp", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("termite", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("octopus", new string[7] { "", "", "", "", "", "", "" } );
            AnimalDictionary.Add("squid", new string[7] { "", "", "", "", "", "", "" } );*/
        }

        private void AddWhales()
        {
            // Aetiocetidae
                // Aetiocetus
            AnimalDictionary.Add("whale1", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "aetiocetus", "cotylalveus" } );
            AnimalDictionary.Add("whale2", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "aetiocetus", "polydentatus" } );
            AnimalDictionary.Add("whale3", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "aetiocetus", "tomitai" } );
            AnimalDictionary.Add("whale4", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "aetiocetus", "weltoni" } );
                // Ashorocetus
            AnimalDictionary.Add("whale5", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "ashorocetus", "eguchii" } );
                // Chonocetus
            AnimalDictionary.Add("whale6", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "chonocetus", "sookensis" } );
                // Fucaia
            AnimalDictionary.Add("whale7", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "fucaia", "buelli" } );
            AnimalDictionary.Add("whale8", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "fucaia", "goedertorum" } );
                // Morawanocetus
            AnimalDictionary.Add("whale9", new string[7] { "animalia", "chordata", "mammalia", "cetartiodactyla", "aetiocetidae", "morawanocetus", "yabukii" } );
        }



        public string GetDictionaryKey(string[] targetValue)
        {
            List<string[]> valuesList = new List<string[]>();
            List<string> keysList = new List<string>();

            var values = AnimalDictionary.Values;
            var keys = AnimalDictionary.Keys;


            foreach (string[] value in values)
            {
                valuesList.Add(value);
            }

            foreach (string key in keys)
            {
                keysList.Add(key);
            }

            int valueIndex = valuesList.IndexOf(targetValue);

            return keysList[valueIndex];
        }

        public void Test()
        {
            if (AnimalDictionary.ContainsValue(AnimalAttributes))
            {
                AnimalType = GetDictionaryKey(AnimalAttributes);
            }
            else
            {
                AnimalType = "none";
            }
        }
    }
}

程序.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Challenge_4___Classification
{
    class Program
    {
        static void Main(string[] args)
        {
            Animal dog = new Animal("animalia", "chordata", "mammalia", "carnivora", "canidae", "canis", "lupus");

            Console.WriteLine(dog.AnimalType);
            dog.Test();
            Console.WriteLine(dog.AnimalType);
            Console.WriteLine(dog.GetDictionaryKey(dog.AnimalAttributes));
            Console.ReadLine();
        }
    }
}

标签: c#

解决方案


问题是您假设此行上的实例是相同的,而事实并非如此。即使值相同, for 的实例targetValue也与插入的实例不同。valuesList

int valueIndex = valuesList.IndexOf(targetValue);

改成:

public string GetDictionaryKey(string[] targetValue)
{
    List<string[]> valuesList = new List<string[]>();
    List<string> keysList = new List<string>();

    var values = AnimalDictionary.Values;
    var keys = AnimalDictionary.Keys;


    foreach (string[] value in values)
    {
        valuesList.Add(value);
    }

    foreach (string key in keys)
    {
        keysList.Add(key);
    }

    var entry = values.FirstOrDefault(r => r.SequenceEqual(targetValue));

    int valueIndex = valuesList.IndexOf(entry);

    return keysList[valueIndex];
}

请注意,数组是引用类型而不是原始类型。.IndexOf当您不使用相同的变量实例时,只能在方法上直接使用原始类型。

数组是允许您将多个项目视为单个集合的机制。Microsoft® .NE​​T 公共语言运行时 (CLR) 支持一维数组、多维数组和交错数组(数组的数组)。所有数组类型都是从 System.Array 隐式派生的,而 System.Array 本身是从 System.Object 派生的。这意味着所有数组始终是在托管堆上分配的引用类型,并且您的应用程序的变量包含对数组的引用,而不是数组本身。

https://msdn.microsoft.com/en-us/library/bb985948.aspx


推荐阅读