Use LINQ to store in Hashtable [duplicate] - c#

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);
}
}
}

Related

How do you assign a dictionary with Lists as values in one statement without using Add()? [duplicate]

This question already has answers here:
Proper way to initialize a C# dictionary with values
(9 answers)
Collection initialization
(5 answers)
Initialize Dictionary<string, List<string>>
(3 answers)
Closed 9 months ago.
I have a dictionary with the value being a list that contains VariableList objects like so
public VariableList {
public string VariableName;
public bool VariableBoolean;
}
Dictionary<string, List<VariableList>> myVariableDictionary;
How would I assign this Dictionary with multiple keys including all the objects in the List in one statement without using Add?
Assuming you already have instances of your VariableList class, you can do something like this:
myVariableDictionary = new Dictionary<string, List<VariableList>>
{
["string1"] = new List<VariableList> { variableList1, variableList2 ... },
["string2"] = new List<VariableList> { variableList3, variableList4 ... },
...
};

How to change the value of Value in a Dictionary [duplicate]

This question already has answers here:
How to update the value stored in Dictionary in C#?
(10 answers)
Closed 2 years ago.
I have a Dictionary<string, int> ad I'd like to amend the int.
I am unable to do so as it's read only.
My effort is
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var itemInList = new Dictionary<string, int>();
itemInList.Add("a", 0);
var existing = itemInList.SingleOrDefault(a => a.Key == "a");
existing.Value++; //fails
}
}
I don't understand what I need to do to fix this
You can use the indexer, like this:
itemInList["a"]++;
That will use the "get" part of the indexer, increment the result, then use the "set" part of the indexer afterwards - so it's equivalent to:
itemInList["a"] = itemInList["a"] + 1;
you are handling the dictionary in wrong way to set a value change your code like this:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var itemInList = new Dictionary<string, int>();
itemInList.Add("a", 0);
itemInList["a"]+=1; //since dictionaries works on keys identifier
//or
++itemInList["a"];
}
}

how to modify the value of an int Key in C# [duplicate]

This question already has answers here:
How to modify key in a dictionary in C#
(4 answers)
Closed 4 years ago.
I have a:
Dictionary<string, Dictionary<int, List<string>>> res = new Dictionary<string,
Dictionary<int, List<string>>>();
and I need to modify/change the int value of the nested Dictionary Key and keep all Dictionary values( List ) for the int Key.
If I understood everything correctly:
res[stringKey].Add(newKey, res[oldKey]);
res[stringKey].Remove(oldKey);
There is no native way to achieve this that I know of but you can try the following:
private void ModifyKey(int oldKey, int newKey, Dictionay<int, List<string>> dict)
{
var data = dict[oldKey];
// Now remove the previous data
dict.Remove(key);
try
{
dict.Add(newKey, data);
}
catch
{
// one already exists..., perhaps roll back or throw
}
}
You would then call the method as follows when you want to change the key:
// Assuming the dictionary is called myData
ModifyKey(5, 7, myData);

Enum to Dictionary LINQ [duplicate]

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#

One key and many different values in Dictionary [duplicate]

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

Categories