This question already has answers here:
Enum to Dictionary<int, string> in C#
(10 answers)
Closed 8 years ago.
I'm trying to convert an Enumeration to a Dictionary using LINQ
Here is what I have so far:
// returns a dictionary populated with the relevant keys
public Dictionary<string, string> StartNewEntry()
{
return Enum.GetNames(typeof(TableDictionary)).ToDictionary(Key =>
(string)Enum.Parse(typeof(TableDictionary), Key), value => "");
}
Its giving me issues when trying to cast the key.
Unable to cast object of type 'InventoryImportExportLibrary.TableDictionary' to type 'System.String'.
I'm looking for this:
public enum TableDictionary
{
Barcode = 0,
FullName = 1,
Location = 2,
Notes = 3,
Category = 4,
Timestamp = 5,
Description = 6
}
With a dictionary thats
["Barcode", ""]
I'm not sure what suits does here. I do want the string because I need to use it later in my program for comparisons.
I think want you really want is
Enum to List See: Convert an enum to List
But if you really need a Dictionary take a look at Enum to Dictionary c#
Related
This question already has answers here:
How can I deserialize a child object with dynamic (numeric) key names?
(2 answers)
Closed 4 years ago.
I have a Json file, with the object serialized correctly, but the problem is that the json has what seems like a dictionary with keys that are strings "0","1" and so on.
Is there any way, not involving writing an own parser, to correctly deserialise these into a list?
"WeaponSlots":{
"0":{
"WeaponInstalled":null,
"AllowedWeaponTypes":{
"0":{
"0":2
}
},
"AllowedWeapons":null
},
"1":{
"WeaponInstalled":null,
"AllowedWeaponTypes":{
"0":{
"0":2
}
},
"AllowedWeapons":null
}
Example file: https://pastebin.com/i3LQ3L7j
You can use the datatype Dictionary<string, object> to deserialize this..
static void Main(string[] args)
{
// load the file.
var file = File.ReadAllText("Example.json");
// to generate the 'Example' classes from JSON I used
// https://app.quicktype.io and changed the name to 'Example'
var example = JsonConvert.DeserializeObject<Example>(file);
// select the value of each dictionary entry into a list.
var sections = example.Sections.Select(x => x.Value).ToList();
}
This question already has answers here:
How can I ignore unknown enum values during json deserialization?
(6 answers)
Closed 4 years ago.
Say I have the following enum:
public enum Test
{
item1 = 1,
item2 = 2,
item3 = 3
}
I add all those enums to a list using JsonConvert.SerializeObject. I then have a JSON string as follows:
["item1","item2","item3"]
I then want to Deserialize the JSON back into a list of the enums. So:
List<Test> list = JsonConvert.DeserializeObject<List<Test>>(json string);
This works, great.
However, if I remove one of the enum items after the list has been serialized I get an error.
So, my enum becomes:
public enum Test
{
item1 = 1,
item3 = 3
}
I now get an error on this line.
List<Test> list = JsonConvert.DeserializeObject<List<Test>>(json string);
The error is:
Error converting value "item2" to type 'Test'
How can I get round this?
I've tired added the following JsonSetting but this made no difference.
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
}
You can just ignore this kind of errors (in example I ignore every error, but you will figure it out for your case):
var result = JsonConvert.DeserializeObject<List<Test>>(json string, new JsonSerializerSettings
{
Error = HandleDeserializationError
});
public void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
errorArgs.ErrorContext.Handled = true;
}
This is part of how enums work in C#, it happens because the enums are defined at compile time and and the deserializer can't figure out what "item2" should be. As Peter asked, what would expect to happen if you didn't get an error?
If you expect your enum values to change frequently, you may want to simulate an enum by using a class that only has named string constants instead. That will allow you some wiggle room for enum values being added/removed, but you'll still need to consider how your program will deal with values it hasn't encountered before!
Edit: On seeing your expectation, you could first deserializing your JSON to a string array, then iterate through your result and tryParse() each string, adding each valid result to the list (or using linq)
This question already has answers here:
Convert Linq Query Result to Dictionary
(4 answers)
Closed 8 years ago.
Is it possible to use LINQ to get data from DB and store it in Dictionary.
I can do LINQ and store it in a List<Class_B> and then iterate through the list and store it in Dictonary<Class_A,List<Class_B>>. But is it possible to directly store in the Dictionary?
System.Linq.Enumerable has a ToDictionary method.
Here's an example from dotnetperls.com:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Example integer array.
int[] values = new int[] { 1, 3, 5, 7 };
// First argument is the key, second the value.
Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true);
// Display all keys and values.
foreach (KeyValuePair<int, bool> pair in dictionary)
{
Console.WriteLine(pair);
}
}
}
This question already has answers here:
Multi Value Dictionary?
(10 answers)
Closed 8 years ago.
How can I store many different values in Dictionary under one key?
I have a code here:
Dictionary<string, DateTime> SearchDate = new Dictionary<string, DateTime>();
SearchDate.Add("RestDate", Convert.ToDateTime("02/01/2013"));
SearchDate.Add("RestDate", Convert.ToDateTime("02/28/2013"));
but in Dictionary i learned that only one unique key is allowed, so my code is producing error.
The simplest way is to make a Dictionary of some sort of container, for example
Dictionary<string,HashSet<DateTime>>
or
Dictionary<string,List<DateTime>>
Use Dictionary<string, List<DateTime>>. Access the list by the key, and then add the new item to the list.
Dictionary<string, List<DateTime>> SearchDate =
new Dictionary<string, List<DateTime>>();
...
public void AddItem(string key, DateTime dateItem)
{
var listForKey = SearchDate[key];
if(listForKey == null)
{
listForKey = new List<DateTime>();
}
listForKey.Add(dateItem);
}
You may try using a Lookup Class. To create it you may use Tuple Class:
var l = new List<Tuple<string,DateTime>>();
l.Add(new Tuple<string,DateTime>("RestDate", Convert.ToDateTime("02/01/2013")));
l.Add(new Tuple<string,DateTime>("RestDate", Convert.ToDateTime("02/28/2013")));
var lookup = l.ToLookup(i=>i.Item1);
However, if you need to modify the lookup, you'll have to modify the original list of tuples and update the lookup from it. So, it depends on how often this collection tends to change.
You can use Lookup class if you are using .NET 3.5
This question already has answers here:
.NET valid property names
(4 answers)
Closed 8 years ago.
can we have property names like $ref #schema ? If so, how ? If not why not ?
I am actually to do something like this
dynamic d = new ExpandoObject();
d.$ref = somevlaue;
but I can't do that?
Also , how do I workaround the fact that keywords can't be property names?
Use
public string #class {get; set;}
for using keywords as variable names. For more information you can see the rules for Identifiers.
Since you are mainly interested in the ExpandoObject, a workaround would be to directly set and/or retrieve those property names by casting the ExpandoObject to an IDictionary<string, Object>:
dynamic d = new ExpandoObject();
var dict = (IDictionary<string, Object>)d;
dict["$ref"] = "haha!";
The language has the guideline of acceptable chars of name. In your case you can try to use #ref.