C# Cannot get dictionary key (string) from value (string[])
I am trying to create an Animal Classification System in C# where you specify the kingdom, phylum, class, order, family, genus and species of an animal and the program outputs what animal it is.
I am using a dictionary to represent all of the animals with a string animalType, string animalAttributes
To get it to work, I need to be able to find the key of a dictionary for a given value, which I created a method for, but I keep getting an out of index error.
I have looked through a few posts already but unfortunately, I couldn't find anything that solved this.
Thanks in advance for your help!
My Code
Animal.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";
}
}
}
}
Program.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#
add a comment |
I am trying to create an Animal Classification System in C# where you specify the kingdom, phylum, class, order, family, genus and species of an animal and the program outputs what animal it is.
I am using a dictionary to represent all of the animals with a string animalType, string animalAttributes
To get it to work, I need to be able to find the key of a dictionary for a given value, which I created a method for, but I keep getting an out of index error.
I have looked through a few posts already but unfortunately, I couldn't find anything that solved this.
Thanks in advance for your help!
My Code
Animal.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";
}
}
}
}
Program.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#
Use the debugger and see what happens at this code line when the exception is being thrown:int valueIndex = valuesList.IndexOf(targetValue);
(Hint: Two different array object instances are not equal, even if they both contain the same elements in the same order. You would need to write a custom comparer for your arrays to make the list lookup work)
– elgonzo
Nov 23 at 1:52
By the way, you don't really need to create temporary keysList and valuesList lists. Remember, aDictionary<TKey, TValue>
is a collection of key-value-pairs:ICollection<KeyValuePair<TKey, TValue>>
. So, instead of the dance with keysList and valuesLists, iterate over this collection (the dictionary) directly to find the key-value-pair which has the value you are looking for (you will still need to do you custom array comparer)
– elgonzo
Nov 23 at 2:15
add a comment |
I am trying to create an Animal Classification System in C# where you specify the kingdom, phylum, class, order, family, genus and species of an animal and the program outputs what animal it is.
I am using a dictionary to represent all of the animals with a string animalType, string animalAttributes
To get it to work, I need to be able to find the key of a dictionary for a given value, which I created a method for, but I keep getting an out of index error.
I have looked through a few posts already but unfortunately, I couldn't find anything that solved this.
Thanks in advance for your help!
My Code
Animal.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";
}
}
}
}
Program.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#
I am trying to create an Animal Classification System in C# where you specify the kingdom, phylum, class, order, family, genus and species of an animal and the program outputs what animal it is.
I am using a dictionary to represent all of the animals with a string animalType, string animalAttributes
To get it to work, I need to be able to find the key of a dictionary for a given value, which I created a method for, but I keep getting an out of index error.
I have looked through a few posts already but unfortunately, I couldn't find anything that solved this.
Thanks in advance for your help!
My Code
Animal.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";
}
}
}
}
Program.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#
c#
asked Nov 23 at 1:46
benWornes
84
84
Use the debugger and see what happens at this code line when the exception is being thrown:int valueIndex = valuesList.IndexOf(targetValue);
(Hint: Two different array object instances are not equal, even if they both contain the same elements in the same order. You would need to write a custom comparer for your arrays to make the list lookup work)
– elgonzo
Nov 23 at 1:52
By the way, you don't really need to create temporary keysList and valuesList lists. Remember, aDictionary<TKey, TValue>
is a collection of key-value-pairs:ICollection<KeyValuePair<TKey, TValue>>
. So, instead of the dance with keysList and valuesLists, iterate over this collection (the dictionary) directly to find the key-value-pair which has the value you are looking for (you will still need to do you custom array comparer)
– elgonzo
Nov 23 at 2:15
add a comment |
Use the debugger and see what happens at this code line when the exception is being thrown:int valueIndex = valuesList.IndexOf(targetValue);
(Hint: Two different array object instances are not equal, even if they both contain the same elements in the same order. You would need to write a custom comparer for your arrays to make the list lookup work)
– elgonzo
Nov 23 at 1:52
By the way, you don't really need to create temporary keysList and valuesList lists. Remember, aDictionary<TKey, TValue>
is a collection of key-value-pairs:ICollection<KeyValuePair<TKey, TValue>>
. So, instead of the dance with keysList and valuesLists, iterate over this collection (the dictionary) directly to find the key-value-pair which has the value you are looking for (you will still need to do you custom array comparer)
– elgonzo
Nov 23 at 2:15
Use the debugger and see what happens at this code line when the exception is being thrown:
int valueIndex = valuesList.IndexOf(targetValue);
(Hint: Two different array object instances are not equal, even if they both contain the same elements in the same order. You would need to write a custom comparer for your arrays to make the list lookup work)– elgonzo
Nov 23 at 1:52
Use the debugger and see what happens at this code line when the exception is being thrown:
int valueIndex = valuesList.IndexOf(targetValue);
(Hint: Two different array object instances are not equal, even if they both contain the same elements in the same order. You would need to write a custom comparer for your arrays to make the list lookup work)– elgonzo
Nov 23 at 1:52
By the way, you don't really need to create temporary keysList and valuesList lists. Remember, a
Dictionary<TKey, TValue>
is a collection of key-value-pairs: ICollection<KeyValuePair<TKey, TValue>>
. So, instead of the dance with keysList and valuesLists, iterate over this collection (the dictionary) directly to find the key-value-pair which has the value you are looking for (you will still need to do you custom array comparer)– elgonzo
Nov 23 at 2:15
By the way, you don't really need to create temporary keysList and valuesList lists. Remember, a
Dictionary<TKey, TValue>
is a collection of key-value-pairs: ICollection<KeyValuePair<TKey, TValue>>
. So, instead of the dance with keysList and valuesLists, iterate over this collection (the dictionary) directly to find the key-value-pair which has the value you are looking for (you will still need to do you custom array comparer)– elgonzo
Nov 23 at 2:15
add a comment |
1 Answer
1
active
oldest
votes
The issue is that you are assuming that the instance on this line is the same which is not. The instance for targetValue
is not the same as the one inserted in the valuesList
even if the values are the same.
int valueIndex = valuesList.IndexOf(targetValue);
Change to:
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];
}
Note that arrays are reference types and not primitive types. Only primitive types can be directly used on the .IndexOf
method when you are not working with the same variable instances.
Arrays are mechanisms that allow you to treat several items as a
single collection. The Microsoft® .NET Common Language Runtime (CLR)
supports single-dimensional arrays, multidimensional arrays, and
jagged arrays (arrays of arrays). All array types are implicitly
derived from System.Array, which itself is derived from System.Object.
This means that all arrays are always reference types which are
allocated on the managed heap, and your app's variable contains a
reference to the array and not the array itself.
https://msdn.microsoft.com/en-us/library/bb985948.aspx
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Based on your initial design, I used.FirstOrDefault
to get the item instance fromvalues
with the same sequence (order) as thetargetValue
by making use of the.SequenceEqual
method. After fetching the instance, it is then used as parameter in the.IndexOf
which yields your desired result. Your initial problem is thattargetValue
's instance is not the same with the one invalues
even when the elements are exactly the same which is why you were getting-1
asvalueIndex
and an index out of bounds exception.
– John Ephraim Tugado
Nov 27 at 6:00
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439760%2fc-sharp-cannot-get-dictionary-key-string-from-value-string%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The issue is that you are assuming that the instance on this line is the same which is not. The instance for targetValue
is not the same as the one inserted in the valuesList
even if the values are the same.
int valueIndex = valuesList.IndexOf(targetValue);
Change to:
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];
}
Note that arrays are reference types and not primitive types. Only primitive types can be directly used on the .IndexOf
method when you are not working with the same variable instances.
Arrays are mechanisms that allow you to treat several items as a
single collection. The Microsoft® .NET Common Language Runtime (CLR)
supports single-dimensional arrays, multidimensional arrays, and
jagged arrays (arrays of arrays). All array types are implicitly
derived from System.Array, which itself is derived from System.Object.
This means that all arrays are always reference types which are
allocated on the managed heap, and your app's variable contains a
reference to the array and not the array itself.
https://msdn.microsoft.com/en-us/library/bb985948.aspx
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Based on your initial design, I used.FirstOrDefault
to get the item instance fromvalues
with the same sequence (order) as thetargetValue
by making use of the.SequenceEqual
method. After fetching the instance, it is then used as parameter in the.IndexOf
which yields your desired result. Your initial problem is thattargetValue
's instance is not the same with the one invalues
even when the elements are exactly the same which is why you were getting-1
asvalueIndex
and an index out of bounds exception.
– John Ephraim Tugado
Nov 27 at 6:00
add a comment |
The issue is that you are assuming that the instance on this line is the same which is not. The instance for targetValue
is not the same as the one inserted in the valuesList
even if the values are the same.
int valueIndex = valuesList.IndexOf(targetValue);
Change to:
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];
}
Note that arrays are reference types and not primitive types. Only primitive types can be directly used on the .IndexOf
method when you are not working with the same variable instances.
Arrays are mechanisms that allow you to treat several items as a
single collection. The Microsoft® .NET Common Language Runtime (CLR)
supports single-dimensional arrays, multidimensional arrays, and
jagged arrays (arrays of arrays). All array types are implicitly
derived from System.Array, which itself is derived from System.Object.
This means that all arrays are always reference types which are
allocated on the managed heap, and your app's variable contains a
reference to the array and not the array itself.
https://msdn.microsoft.com/en-us/library/bb985948.aspx
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Based on your initial design, I used.FirstOrDefault
to get the item instance fromvalues
with the same sequence (order) as thetargetValue
by making use of the.SequenceEqual
method. After fetching the instance, it is then used as parameter in the.IndexOf
which yields your desired result. Your initial problem is thattargetValue
's instance is not the same with the one invalues
even when the elements are exactly the same which is why you were getting-1
asvalueIndex
and an index out of bounds exception.
– John Ephraim Tugado
Nov 27 at 6:00
add a comment |
The issue is that you are assuming that the instance on this line is the same which is not. The instance for targetValue
is not the same as the one inserted in the valuesList
even if the values are the same.
int valueIndex = valuesList.IndexOf(targetValue);
Change to:
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];
}
Note that arrays are reference types and not primitive types. Only primitive types can be directly used on the .IndexOf
method when you are not working with the same variable instances.
Arrays are mechanisms that allow you to treat several items as a
single collection. The Microsoft® .NET Common Language Runtime (CLR)
supports single-dimensional arrays, multidimensional arrays, and
jagged arrays (arrays of arrays). All array types are implicitly
derived from System.Array, which itself is derived from System.Object.
This means that all arrays are always reference types which are
allocated on the managed heap, and your app's variable contains a
reference to the array and not the array itself.
https://msdn.microsoft.com/en-us/library/bb985948.aspx
The issue is that you are assuming that the instance on this line is the same which is not. The instance for targetValue
is not the same as the one inserted in the valuesList
even if the values are the same.
int valueIndex = valuesList.IndexOf(targetValue);
Change to:
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];
}
Note that arrays are reference types and not primitive types. Only primitive types can be directly used on the .IndexOf
method when you are not working with the same variable instances.
Arrays are mechanisms that allow you to treat several items as a
single collection. The Microsoft® .NET Common Language Runtime (CLR)
supports single-dimensional arrays, multidimensional arrays, and
jagged arrays (arrays of arrays). All array types are implicitly
derived from System.Array, which itself is derived from System.Object.
This means that all arrays are always reference types which are
allocated on the managed heap, and your app's variable contains a
reference to the array and not the array itself.
https://msdn.microsoft.com/en-us/library/bb985948.aspx
edited Nov 23 at 6:22
answered Nov 23 at 2:17
John Ephraim Tugado
3,6511421
3,6511421
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Based on your initial design, I used.FirstOrDefault
to get the item instance fromvalues
with the same sequence (order) as thetargetValue
by making use of the.SequenceEqual
method. After fetching the instance, it is then used as parameter in the.IndexOf
which yields your desired result. Your initial problem is thattargetValue
's instance is not the same with the one invalues
even when the elements are exactly the same which is why you were getting-1
asvalueIndex
and an index out of bounds exception.
– John Ephraim Tugado
Nov 27 at 6:00
add a comment |
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Based on your initial design, I used.FirstOrDefault
to get the item instance fromvalues
with the same sequence (order) as thetargetValue
by making use of the.SequenceEqual
method. After fetching the instance, it is then used as parameter in the.IndexOf
which yields your desired result. Your initial problem is thattargetValue
's instance is not the same with the one invalues
even when the elements are exactly the same which is why you were getting-1
asvalueIndex
and an index out of bounds exception.
– John Ephraim Tugado
Nov 27 at 6:00
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
"Only primitive types can be directly used on the .IndexOf method when you are not working with the same variable instances" That is incorrect. The only thing that decides whether one can use IndexOf "directly" is whether the involved element types are equatable. Depending on the particular collection type on which IndexOf is executed, the specific definition of what constitutes equatable types might differ (as an example, see arrays vs. generic collections). (1/2)
– elgonzo
Nov 23 at 3:03
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
(2/2) Also, many collection types accept some form of custom comparer, allowing to use IndexOf directly even if the element types involved are not equatable by themselves. Whether an element type is primitive or not is of little importance (examples: string is no primitive type, nor is a delegate type, yet both are equatable)
– elgonzo
Nov 23 at 3:08
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
I stand corrected then. Thank you for your insight.
– John Ephraim Tugado
Nov 23 at 6:20
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Thanks for this, it worked. I'm not quite sure how it works though, can you explain it?
– benWornes
Nov 23 at 20:02
Based on your initial design, I used
.FirstOrDefault
to get the item instance from values
with the same sequence (order) as the targetValue
by making use of the .SequenceEqual
method. After fetching the instance, it is then used as parameter in the .IndexOf
which yields your desired result. Your initial problem is that targetValue
's instance is not the same with the one in values
even when the elements are exactly the same which is why you were getting -1
as valueIndex
and an index out of bounds exception.– John Ephraim Tugado
Nov 27 at 6:00
Based on your initial design, I used
.FirstOrDefault
to get the item instance from values
with the same sequence (order) as the targetValue
by making use of the .SequenceEqual
method. After fetching the instance, it is then used as parameter in the .IndexOf
which yields your desired result. Your initial problem is that targetValue
's instance is not the same with the one in values
even when the elements are exactly the same which is why you were getting -1
as valueIndex
and an index out of bounds exception.– John Ephraim Tugado
Nov 27 at 6:00
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439760%2fc-sharp-cannot-get-dictionary-key-string-from-value-string%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Use the debugger and see what happens at this code line when the exception is being thrown:
int valueIndex = valuesList.IndexOf(targetValue);
(Hint: Two different array object instances are not equal, even if they both contain the same elements in the same order. You would need to write a custom comparer for your arrays to make the list lookup work)– elgonzo
Nov 23 at 1:52
By the way, you don't really need to create temporary keysList and valuesList lists. Remember, a
Dictionary<TKey, TValue>
is a collection of key-value-pairs:ICollection<KeyValuePair<TKey, TValue>>
. So, instead of the dance with keysList and valuesLists, iterate over this collection (the dictionary) directly to find the key-value-pair which has the value you are looking for (you will still need to do you custom array comparer)– elgonzo
Nov 23 at 2:15