One-liner to create a dictionary with one entry - c#

I have a method which takes a Dictionary<int, int> as a parameter
public void CoolStuff(Dictionary<int, int> job)
I want to call that method with one dictionary entry, such as
int a = 5;
int b = 6;
var param = new Dictionary<int, int>();
param.Add(a, b);
CoolStuff(param);
How can I do it in one line?

This is it, if you do not need the a and b variables:
var param = new Dictionary<int, int> { { 5, 6 } };
or even
CoolStuff(new Dictionary<int, int> { { 5, 6 } });
Please, read How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)

var param = new Dictionary<int, int>() { { 5, 6 } };

Related

How to avoid dictionary override reference value of object when apply Dictionary.Clear()

I am working on .NET CORE 6. I have nested Dictionary<int, string> where I am adding value in loop to nested dictionary from string. The string holds multiple record where each record holds 15 columns hence dictionary is useful to hold keys.
After 15 iteration, I add nested/ child dictionary to parent Dictionary<string, string> and then I set nested dictionary to start again from counter 0. The issue is once I clear nested dictionary using Clear(), it also clear data from Parent dictionary. I need help on this and how I can approach to avoid that, dataItemDictionary.Clear();
private Dictionary<string, Dictionary<int, string>> ConvertStream(string stream)
{
Dictionary<string, Dictionary<int, string>> dataDictionary = new Dictionary<string, Dictionary<int, string>>();
Dictionary<int, string> dataItemDictionary = new Dictionary<int, string>();
if (!string.IsNullOrWhiteSpace(stream))
{
string column = string.Empty;
int dataItemDictionaryindex = 0;
int dataDictionaryIndex = 0;
int columnCounter = 16;
foreach(char c in stream)
{
if(c.Equals('|'))
{
dataItemDictionary.Add(dataItemDictionaryindex, column);
column = string.Empty;
dataItemDictionaryindex++;
if (columnCounter == dataItemDictionaryindex)
{
Dictionary<int, string> data = new Dictionary<int, string>();
data = dataItemDictionary; // need help here...
dataDictionary.Add("Record#" + dataDictionaryIndex, data);
dataItemDictionary.Clear();
dataDictionaryIndex++;
columnCounter = columnCounter * (dataDictionaryIndex + 1);
}
}
else
{
if (!c.Equals('\r') && !c.Equals('\n'))
{
column = column + c;
}
}
}
}
return dataDictionary;
}
Dictionary<TKey, TValue> is a reference type. Use the copy constructor of Dictionary<TKey, TValue> to create a new collection instance.
Dictionary<int, string> data = new Dictionary<int, string>(dataItemDictionary);

How to link a string key to a function in a c# dictionary

I am currently programming using Unity and C#, and I have trouble linking a string value to a function using a dictionary.
I think of a code looking like this :
private string name;
void function1()
{
// code
}
private Dictionary<string, ?function?> nameToFunction = new Dictionary<string, ?function?>();
// The part between interrogation marks being unknown to me
// Trying to call the function with the name
nameToFunction[name]
I am sorry if my question isn't relative, or if there are simpler solutions I haven't thought of, but I am starting to learn programming.
Thanks for your answers !
Here are some examples:
private Dictionary<string, Action> actionDict = new Dictionary<string, Action>();
private Dictionary<string, Action<int>> actionParamDict = new Dictionary<string, Action<int>>();
private Dictionary<string, Func<int>> funcDict = new Dictionary<string, Func<int>>();
private Dictionary<string, Func<int, string>> funcParamDict = new Dictionary<string, Func<int, string>>();
You use Action e.g. Action<input type1, input type 2> if not returning a value, and Func<input type1, input type2, output type> to return a value. Both are defined with multiple numbers of inputs. So you could do Func<int,int,int,bool> for example, and Action<int,int,bool,string,string>
Here's a few examples:
var dict = new Dictionary<string, Action>();
dict.Add("Hello", () => Console.WriteLine("Hello"));
dict.Add("Goodbye", () => Console.WriteLine("Goodbye"));
dict["Hello"]();
dict["Goodbye"]();
var dict2 = new Dictionary<string, Action<string>>();
dict2.Add("HelloName", (name) => Console.WriteLine($"Hello {name}"));
dict2["HelloName"]("Fred");
var dict3 = new Dictionary<string, Func<int, int, int>>();
dict3.Add("ADD", (n1, n2) => n1 + n2);
dict3.Add("SUBTRACT", (n1, n2) => n1 - n2);
Console.WriteLine($"{dict3["ADD"](5, 10)}");
Console.WriteLine($"{dict3["SUBTRACT"](10, 5)}");
//create dict with var objects s0, s1, s2 dynamically
Dictionary<String, Object> dictionary = new Dictionary<String, Object>();
for(int i=0; i<sWPaths.Length-1; i++) {
string name = String.Format("s{0}", i);
dictionary[name] = i.ToString();
}
foreach (string p in found){
//change to your desired variable using string.format method
if(dictionary.Contains[p]) {
dictionary[p] = found.ToString();
}
}

What data type to use in C#?

I need save some values in array by key, for example:
var arr = ['N' => 1, 'M' => 2, 'P' => 3];
What data type I need use in C# for this?
I tried ArrayList class, but it does a simple array.
You want to use a Dictionary.
Complete example:
using System.Collections.Generic;
class Program
{
static void Main()
{
var arr = new Dictionary<char, int> {
{'N', 1},
{'M', 2},
{'P', 3},
};
foreach (var pair in arr) {
System.Console.WriteLine(pair.Key + ": " + pair.Value);
}
}
}
An IDictionary<string, int> should do the trick. Something like:
var arr = new Dictionary<string, int>
{
{ "N", 1 },
{ "M", 2 },
{ "P", 3 }
};
(Or even an IDictionary<char, int> if those values should be char instead of string.)
What you want to use is a System.Collections.Generic.Dictionary<char, int> or Dictionary<string, int> or you can also use an enum such as:
public enum EnumName
{
N,
M,
P
}
Try using Dictionary<string, int>, or Dictionary` if you wish to reference multiple types of values.
Have you tried a Hashtable, it would allow the key value pairs

How to reverse the index in array of dictionaries?

My array dictionary key value pairs are similar to this
[0]
key : x
value : 1
[1]
key : y
value : 2
[2]
key : z
value : 3
But I need to reverse the index of the dictionary. I need to convert the above dictionary to this :
[0]
key : z
value : 3
[1]
key : y
value : 2
[2]
key : x
value : 1
I tried Reverse() function. But it didn't work. I don't know how to achieve this. Can anyone help me with this ?
How can I achieve this ?
You shouldn't assume dictionaries are ordered. They aren't.
If you want to have an array that is ordered, you should use a SortedDictionary. You can also reverse the order in there if you want to. You should use a custom comparer for that (altered from here):
class DescendedStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
int ascendingResult = Comparer<string>.Default.Compare(x, y);
// turn the result around
return 0 - ascendingResult;
}
}
//
SortedDictionary<string, string> test
= new SortedDictionary<string, string>(new DescendedDateComparer());
You can iterate over it with foreach for example. The results will be ordered descending.
the function Enumerable.Reverse() returns an IEnumerable not an array. Did you forget to make the reversed sequence an array? The following worked for me:
class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, int>();
dict.Add("x", 1);
dict.Add("y", 2);
dict.Add("z", 3);
var reversed = dict.ToArray().Reverse();
var reversedArray = reversed.ToArray();
Console.ReadKey();
}
}
I tried reverse method, it worked. Please see below images. I used VS 2013, .Net 4.5
Output generated
You should use SortedDictionary and pass a key on construction
public sealed class CompareReverse<T> : IComparer<T>
{
private readonly IComparer<T> original;
public CompareReverse(IComparer<T> original)
{
this.original = original;
}
public int Compare(T left, T right)
{
return original.Compare(right, left);
}
}
and in your main call
var mydictionary = new SortedDictionary<int, string>(
new CompareReverse<int>(Comparer<int>.Default));
for eg:-
var mydictionary = new SortedDictionary<int, string>(
new CompareReverse<int>(Comparer<int>.Default));
dictionary.add(1, "1");
dictionary.add(2, "2");
dictionary.add(3, "3");
dictionary.add(4, "4");
SortedDictionary sorts by key, not by value.
Here's a clean way to reverse the order of values in a Dictionary:
List<KeyValuePair<string, string>> srcList = aDictionary.ToList();
srcList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
Dictionary<string, string> outputDictionary = new Dictionary<string, string>();
int listCount = srcList.Count;
for(int i = 0; i < listCount; i++) {
int valueIndex = i + 1;
outputDictionary.Add(srcList[i].Key, srcList[valueIndex]);
}
If what you want as output is a List of KeyValuePairs rather than a Dictionary, you can replace the final 6 lines of code in my example with this:
List<KeyValuePair<string, string>> destList = new List<KeyValuePair<string, string>>();
int listCount = srcList.Count;
for(int i = 0; i < listCount; i++) {
int valueIndex = i + 1;
destList.Add(new KeyValuePair<string, string>(srcList[i].Key, srcList[valueIndex]));
}
You can do this :
for (var i = dictionary.Count - 1; i >= 0; i--)
dictionary.Values.ElementAt(i), dictionary.Keys.ElementAt(i);
EDIT : Go here -> how to iterate a dictionary<string,string> in reverse order(from last to first) in C#?

Create a dictionary with arrays as values

I'm trying to initialize a dictionary with string elements as keys and int[] elements as values, as follows:
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};
But the debugger keeps saying: "Unexpected symbol '{'".
Could you tell me what's wrong with the above code?
Thank you!
I am not sure for c# but the following works in Java for example:
instead of
{1,1}
try
new int[]{1,1}
or
new[]{1,1}
Below are two examples that work. The second example only works inside a method. The first example will work inside a method or outside a method in a class.
The initial code was missing the () for the new Dictionary() statement which is probably what gave the "{" unexepcted symbol error. The "new Int[]" is also required
class SomeClass
{
Dictionary<string, int[]> myDictionary = new Dictionary<string, int[]>()
{
{"length", new int[] {1,1} },
{"width", new int[] {1,1} },
};
public void SomeMethod()
{
Dictionary<string, int[]> myDictionary2;
myDictionary2 = new Dictionary<string, int[]>()
{
{"length", new int[] {1,1} },
{"width", new int[] {1,1} },
};
}
}
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> { { "length", new int[] { 1, 1 } }, { "width", new int[] { 1, 1 } } };
You will need to specify that it's an array that you are inserting in to your Dictionary:
System.Collections.Generic.Dictionary<string, int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> {{"length", new int[]{1,2}},{ "width",new int[]{3,4}}};
In addition to all good answers you can also try this.
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
If possible prefer List<> over arrays as resizing is difficult in Arrays. You can not delete an element from an array. But an element can be deleted from List.

Categories

Resources