Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
void Convert(string word)
{
var dictionary = (JObject)JsonConvert.DeserializeObject(dictionaryJson.text);
if(dictionary[word] != null)
{
dictionary[word].ToObject<VocabularyModel>();
// do something;
}
else
{
// do something;
}
}
I am using (JObject)JsonConvert.DeserializeObject to convert json to var dictionary. Everything works fine. However I only have 1 json file and every time a use the function I have to:
var dictionary = (JObject)JsonConvert.DeserializeObject(dictionaryJson.text);
Is there any way to call that line only one and the var dictionary is saved as global variable or something similar that help me call the above command only one time only.
And one other question: does the dictionary[word] works like a loop in an array? Does it go through the dictionary one by one and search for the key "[word]" ?
You can move the declaration of into a class-level scope.
class WhatEverYourClassNameIs
{
private var dictionary;
// Deserializing in constructor, but you can do it elsewhere
WhatEverYourClassNameIs()
{
dictionary = (JObject)JsonConvert.DeserializeObject(dictionaryJson.text);
}
void Convert(string word)
{
// This function and all other functions within your class will have access to dictionary
}
}
Regarding your second question, I don't have a concrete answer since the documentation doesn't say so. A normal .NET dictionary has O(1) indexing complexity, meaning that it doesn't take longer the more elements you have in the dictionary. If you want to be certain you'd have to look up the source code and see how indexing is accomplished in the JObject class
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am developing an AI text communication engine, and I was wondering if anyone point me in the direction of a more efficient approach to validating user input other than just switch / if statements.
This is the foundation of it:
void Update(){
string s = Console.Read()s.ToLower();
if (s == "c1"){
// do 1
}
else if (s == "c2"){
// do 2
}
...
else if (s == "c9342"){
// do 9342
}
}
I should add, I have the ability to check for keywords in the sentence.
I feel like due to the fact that all input is strings, and it is dealing with language, this may be the only way to go, but if anyone has any better approach eg. interfaces, custom types, reflection, threading or anything then I am all ears.
Thanks, Andy
Andy! You can work with delegates to achieve that flexibility. Delegates are a little complex and not as fast as a "direct" code, but they have their value.
Here I'm assuming that your comparison object will always be a string (and a lot of other stuff, if this solution doesn't fit your need, please leave a comment so we can work on that).
// Create a dictionary where the key is your comparison string and
// the action is the method you want to run when this condition is matched
Dictionary<string, Action> ifs = new Dictionary<string,Action>()
{
// Note that after the method name you should not put ()
// otherwise you would be invoking this method instead of create a "pointer"
{"c1", ExecuteC1},
{"c2", ExecuteC2},
{"c9342", ExecuteC9342},
}
private void ExecuteC1()
{
Console.WriteLine("c1");
}
private void ExecuteC2()
{
Console.WriteLine("c2");
}
private void ExecuteC9342()
{
Console.WriteLine("c9342");
}
public RunCondition(string condition)
{
// Get the condition related value by its key and calls the method with 'Invoke()'
ifs[condition].Invoke();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a dictionary that I would like to pass externally through a property but I would like to limit some features like the clear method. Here's the code that i've implemented.
// dictionary private declaration inside the class
private Dictionary<int, string> _value = new Dictionary<int, string>();
// here's the property declaration for access the dictionary outside the class
public new Dictionary<int, string> Value
{
get
{
return _value;
}
set
{
// here is where i'd like to avoid some dictionary features like clear() and give only the opportunity to add or change existing values
_value = value;
}
}
It’s possible through the “set” of this property to limit some of the features of the dictionary? Maybe using a switch or an if statement?
There are a ReadonlyDictionary that acts as a wrapper around a dictionary, and a corresponding IReadOnlyDictionary interface.
If you are on .Net core 3 there is also an ImmutableDictionary if the dictionary never needs to be changed.
If this is to coarse grained, you can always create your own wrapper that works however you want it to.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Sorry, this is kind of a stupid question. So I’m making myself a personal assistant. I have an array of commands and for each one I have a function. If the user types in a command, how to I get it to go run the function?
Let's define some commands as void methods with no return value.
private void DoCommand1() {
Console.WriteLine("executing command 1");
}
private void DoCommand2() {
Console.WriteLine("executing command 2");
}
You can use a Dictionary to map strings to functions:
var commands = new Dictionary<string, Action>();
commands.Add("command1", () => DoCommand1());
commands.Add("command2", () => DoCommand2());
and then run a command from a string:
string myCommand = "command2";
commands[myCommand].Invoke(); //will print "executing command 2"
You should have a look at delegates and Action Delegates in C#.
You want to make some strongly type input and handle those input in C#. Here is how it can be done.
Make a Enum with all the command that you want to strongly type like Login, Logout for example.
Make a dictionary of
private readonly Dictionary<string, StronglyTypedCommands> localBotCommands = new Dictionary<string, StronglyTypedCommands>();
store some static string for what input you will get and what kind of command it is.
In the method you can figure out what exactly input is by help of this Dictionary.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I honestly could not think of a title...anyways
I am trying to create a type
public enum AssemblyType{
Name = "NameOfFile.dll",
}
In then in the unity inspector I would have a list of this type
public List<AssemblyType> requiredAssemblies = new List<AssemblyType> ();
And my expectation is that I will see a list where I can set a list of dropdown boxes to the Name of the AssemblyType
For example this
Inside of this
In case you dont get the image
Day Colours would be the list requiredAssemblies and size would be like Culling Mask on the first image
Sorry forgot what went wrong with the above method
This method returns this error in unity
Assets/Scripts/WebSharp.cs(21,16): error CS0029: Cannot implicitly convert typestring' to int'
sorry my problem was clearly stated
from the error I would(as anyone i hope) realize that an enum is an int value
My question what should I be replacing the enum with since a string cannot exist outside of a class
This
public enum AssemblyType{
Name = "NameOfFile.dll",
}
...doesn't compile. So I'm not sure what the question is.
If you're just trying to define a list of DLL names, you just need to replace this
public List<AssemblyType> requiredAssemblies = new List<AssemblyType> ();
with this
public List<string> requiredAssemblies = new List<string>
{
"NameOfFile.dll",
"NameOfOtherFile.dll",
"Et cetera"
};
If you need to expose a simpler name to the user, but let the application remember the original name, you can use a dictionary:
public Dictionary<string,string> requiredAssemblies = new Dictionary<string,string>
{
{"NameOfFile1.dll",#"c:\SomeLongPath\NameOfFile2.dll"},
{"NameOfFile2.dll",#"c:\SomeLongPath\NameOfFile2.dll"},
{"NameOfFile3.dll",#"c:\SomeLongPath\NameOfFile3.dll"}
};
..and then populate your controls using the list returned by requiredAssemblies.Keys. You can then use the user's selection to look up the full path in the dictionary when you need it.
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 9 years ago.
Improve this question
Is there a broad aversion in the C# community to modifying parameters? For example, would a popular style-checker complain about the parameter reassignment aspect of the following?
public void Create(Template template = null) {
if (template == null) template = GetDefaultTemplate();
// ...
}
An alternative to this would be the following, but assuming code blocks are appropriately small, it's probably not any clearer:
public void Create(Template template = null) {
var theActualTemplate = template ?? GetDefaultTemplate();
// ...
}
I apologize for this surely tired/already-answered question, but oddly I can't find anything on it. I tried looking through some C# style guides (including all the ones here: Style guide for c#?), but didn't find this issue covered. Maybe it's a non-issue?
If you have a relatively authoritative source for this, I'd love to hear it.
In your sample you are just modifying the variable inside your method scope. Since that is your local variable, your method can do with it whatever it wants - it does not impact the caller. In general it is better to use the same variable because it makes the code easier to maintain - if you create a new variable, you increase the risk of accidentally using the wrong one and get NullReferenceException.
If you would be using ref keyword only then the assignment will impact the caller.
It can be useful when you need to set a default value for a reference type, because you can't really specify it like you would do for a value type.
public void Create(int templateId = 1) {
// this will compile
// ...
}
public void Create(Template template = GetDefaultTemplate()) {
// this WON'T compile
// ...
}
Using null as a default value for a reference type can help you defining a default object for your parameter.