This question already has answers here:
C# dictionary - one key, many values
(15 answers)
Multi Value Dictionary?
(10 answers)
Dictionary one key many values in code c#
(4 answers)
Closed 3 years ago.
I was wondering about the best way to map one value to many in a dictionary (or some other structure) in C#.
What I wanted to do is something like this:
public GenreToEntity = new Dictionary<string, string[]>()
{
{ "filmes", ["Filme"] },
{ "programas", ["Jornalismo", "Variedade", "Série/seriado"] }
};
But it should be static, so I don't want to add values line by line.
Is that possible?
I got it! The missing part was what #itsme86 suggested:
public static Dictionary<string, List<string>> EntityToGenre = new Dictionary<string, List<string>>()
{
{ "filmes", new List<string>() {"Filme"} },
{ "novelas", new List<string>() {"Novela"} },
{ "programas", new List<string>() {"Jornalismo", "Variedade", "Série/seriado", "Outros" } }
};
Related
This question already has answers here:
Group by array contents
(1 answer)
Easiest way to compare arrays in C#
(19 answers)
Closed 2 years ago.
I've a lsit of type List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>();
foreach (string entry in results)
{
FileInfo fileInfo = new FileInfo(Path.Combine("DirectoryPath"), entry));
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(fileInfo.FullName))
{
var hash = md5.ComputeHash(stream);
fileHashList.Add(new KeyValuePair<byte[], string>(hash, fileInfo.FullName));
}
}
}
I need to find all the duplicate keys in this list.
I tried this but doesn't work in my case, I get "Enumeration yielded no results" even though I've same keys!
Let me know if any additional data is needed
Thanks
This question already has answers here:
Get dictionary key by value
(11 answers)
Closed 2 years ago.
This is my function where I created a dictionary:
public int Scale(string value)
{
//some calculs
int result = 19; // or int between 0 and 40
this.stringToInt = new Dictionary<string, int>()
{
{"1p",00},{"2p",01},{"3p",03} ... {"300p",40}
};
// Here I try to do something like that: if(result == (int in dictionary) return associate string
}
I tried the below code:
if (this.stringToInt.ContainsValue(result)
{
return this.stringToInt[result]; // I don't know what to write between hook (result doesn't work).
}
I don't know how to return associate string.
Thank you in advance for help!
var keyValuePair = this.stringToInt.FirstOrDefault(x => x.Value == result);
if (!keyValuePair.Equals(new KeyValuePair<string, int>()))
{
// found, use keyValuePair.Key
}
This would work i guess using Linq. But only returns the first found value. If the value is more than once in the dictionary, only the first one found is returned.
But you should do it like in the comment from #nanu_nana
This question already has answers here:
C#: how to get an object by the name stored in String?
(4 answers)
Get value of a variable using its name in a string
(2 answers)
Getting variable by name in C#
(1 answer)
Closed 3 years ago.
I have created multiple List and want to use each individual List when I have a variable name.
For example:
private List<string> listAlabama = new List<string>();
private List<string> listTexas = new List<string>();
// fill Lists with values
//Call Method to assign state to correct list
AssignNameToList("Alabama");
private void AssignNameToList(string state)
{
// Assign variable to the correct List e.g
sring tempFindList="list"+state;
//Use the right List
string tempVal=tempFindList[0]???
// should be listAlabama
}
Below is the solution I came up with using a Dictionary
var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("Alabama", listAlabama);
dictionary.Add("Texas", listTexas);
switch (tempState)
{
case "Alabama":
List<string> value = dictionary["Alabama"];
Console.WriteLine(value);
string[] tempArray = value[totalPopulationIdx].Split(',');
This question already has answers here:
Multi-key dictionary in c#? [duplicate]
(16 answers)
Closed 4 years ago.
hi how could I make array like this in c#??:
settings width and height is loaded from file
properties["settings"]["width"] = "bbb";
properties["settings"]["height"] = "cccc";
and dynamic_string_key is keys loaded from file and I dont know how many or what key name and values will be :)
properties["sets_of_data"][dynamic_string_key]= "lalala";
properties["sets_of_data"][dynamic_string_key]= "lalala";
properties["sets_of_data"][dynamic_string_key]= "lalala";
properties["sets_of_data"][dynamic_string_key]= "lalala";
Arrays in C# only allow you to find an element by the index (integer), not by an arbitrary string. In C#, that's a Dictionary<>.
You can use a dictionary of a dictionary, but it's not as easy:
var data = new Dictionary<string, Dictionary<string, string>>();
data["settings"] = new Dictionary<string, string>();
data["settings"]["width"] = "bbb";
But that seems overly complicated. If you know you'll have "settings", then it's probably more readable to just have one dictionary for settings:
var settings = new Dictionary<string, string>();
settings["width"] = "bbb";
If your file is JSON you can use JSON.NET and do it like this
JObject obj = JObject.Parse(File.ReadAllText("foo.json"));
var bar = (string)obj["foo"]["bar"];
you can use
Dictionary<string, Dictionary<string, string>> properties =
Dictionary<string, Dictionary<string, string>>
{
{
"settings",
new Dictionary<string, string>
{
{"width", "200"},
{"height", "150"},
}
}
};
Or you can use Tuples, especially named tuples
var exampleNamedTuple = (Height: 0, Width: 0, Value: "");
var list = new List<(int Height, int Width, string Value)>();
list.Add(exampleNamedTuple);
var height = list.First().Height;
var width = list.First().Width;
var value = list.First().Value;
then you can assign it to your settings property.
https://learn.microsoft.com/en-us/dotnet/csharp/tuples
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
C# Initialize Object With Properties of Another Instance
(A) I can do this...
var newRestaurant = new Restaurant();
newRestaurant.Cuisine = model.Cuisine;
newRestaurant.Name = model.Name;
(B) And I can write it this way...
var newRestaurant = new Restaurant() { Name = model.Name };
(C) But how come I can't write it like so...
var newRestaurant = new Restaurant() model;
(Q) Isn't (B) just an Object-Literal while (C) is an object instance?
Would love to know.
Thx
Isn't (B) just an Object-Literal while (C) is an object instance?
The short answer? No. C# doesn't use curly braces to represent object literals like JavaScript or similar languages do; C# uses curly braces to refer to blocks.
In the code
var newRestaurant = new Restaurant() { Name = model.Name };
the { Name = model.Name } part isn't an object literal, it's an initializer block. You can use a similar syntax to initialize collections like lists and dictionaries:
var myString = "string3";
var myList = new List<string>() { "string1", "string2", myString };
var myDictionary = new Dictionary<string, int>()
{
{ "string1", 1 },
{ "string2", 2 },
{ myString, 3 },
};
As you can see, the syntax of these blocks differs based on what sort of object is before them. This code is transformed by the compiler into
var myString = "string3";
var myList = new List<string>();
myList.Add("string1");
myList.Add("string2");
myList.Add(myString);
var myDictionary = new Dictionary<string, int>();
myDictionary.Add("string1", 1);
myDictionary.Add("string2", 2);
myDictionary.Add(myString, 3);
And in the case of your example, it's transformed into:
var newRestaurant = new Restaurant();
newRestaurant.Name = model.Name;
When you try and use model like var newRestaurant = new Restaurant() model;, the compiler has no idea what sorts of properties are in model or what you meant to do with them; are you trying to add to a list? Are you trying to copy all the properties? What does it do if all the properties in model don't match?
Further reading
Later versions of C# will have something called Records, which will have a similar feature to what you're describing (copying fields from one thing to another). You can read about them on the compiler's github page if you're interested, but it's pretty technical.