I have
Dictionary idDictionary = new Dictionary();
within this Dictionary, I want, add two row with same key but values different
I used this Dictionary in many methods that a global Dictionary in one method has that issue. if I changed like all u suggest another method get error
Try something like this.
Dictionary<string, List<string>> obj = new Dictionary<string, List<string>>();
List<string> keyValue = new List<string>();
keyValue.Add("a");
keyValue.Add("b");
obj.Add("key1", keyValue);
foreach (KeyValuePair<string, List<string>> entry in obj)
{
// do something with entry.Value or entry.Key
}
List<string> keyValueOutput = new List<string>();
if (obj.TryGetValue("key1",out keyValueOutput))
{
foreach (string s in keyValueOutput)
{
// do something with entry.Value or entry.Key
}
}
Related
Is it possible in C# to create a list and name it from a variable or similar?
Let's say I have a list with 10 rows in it:
a, b, c, d, e, f, g, h, i, j
Can I make 10 lists from this list, each having a name like one of the rows?
Something like
List<string> myList = new List<string>();
foreach (var line in myList)
{
List<string> line = new List<string>();
}
What I want is to make a few lists to store data in, but I won't know the names before the program runs so it needs to generate those dynamically.
Sounds like you want a Dictionary of List<string>s:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
dict.Add(line, new List<string>());
}
Now you can access each list based on the original string we used for the key:
List<string> aList = dict["a"];
You could try something like this:
var newList = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
newList.Add(line, new List<string>());
}
This will give you the data structures in which to store your new data and will allow you to reference them based on the names in the first list.
It seems that you want a Dictionary<String, List<String>> like this:
var data = myList
.ToDictionary(line => line, line => new List<string>());
And so you can
check if "variable" exists
if (data.ContainsKey("z")) {...}
address "variable"
data["a"].Add("some value");
add "variable"
data.Add("z", new List<string>());
I have a Dictionary<string, List<string>>, I used to get back to value using
List<string> keyDicoList = DictErrorCorrectionBeforeJS.Keys.ToList();
List<string> listValue = DictErrorCorrectionBeforeJS.SelectMany(x => x.Value).ToList();
But it seems on production ae using ASP.NET 2.0 when we Dev in 4.0...
So I try to recover them with another way.I find for the Key :
foreach (string key in DictErrorCorrection.Keys)
{
keyDicoList.Add(key);
}
But i have trouble getting the value. As it is not a simple value but a List inside the Dictionnary. I can't do a foreach on it and it seems as it is an enumerator that I can't just go for a for loop, with just adding the Dico.Values[x] to my listValue
How should I proceed to get all the dictionary.value inside my listValue ?
You can just iterate over them using a foreach. The dictionary enumerator yields a KeyValuePair<string, List<string>>:
foreach (KeyValuePair<string, List<string>> kvp in dictionary)
{
string key = kvp.Key;
List<string> list = kvp.Value;
foreach (string listItem in list)
{
// .. use the item, or skip the foreach and use the list at once
}
}
Typically, you enumerate the KVP set of the dictionary:
List<string> values = new List<string>();
foreach (KeyValuePair<string, List<string>> kvp in dict)
{
values.AddRange(kvp.Value); // kvp.Value is List<string>
}
I am having
Dictionary<String, List<String>> filters = new Dictionary<String, List<String>>();
which is having values like country = us. till now I am able to add it when key is not repeated. now when key country is repeated. it is showing that the key is already present.
what I want is How to add multiple values in the same key. I am not able to do it. Please suggest something.
for (int i = 0; i < msgProperty.Value.Count; i++)
{
FilterValue.Add(msgProperty.Value[i].filterValue.Value);
filterColumn = msgProperty.Value[i].filterColumnName.Value;
filters.Add(filterColumn, FilterValue);
}
what I want
country = US,UK
The different types of all your variables are a bit confusing, which won't help you writing the code. I'm assuming you have a Dictionary<string, List<string>> where the key is a "language" and the value is a list of countries for that language, or whatever. Reducing a problem to a minimal set that reproduces the issue is very helpful when asking for help.
Anyway assuming the above, it's as simple as this:
Try to get the dictionary["somelanguage"] key into existingValue.
If it doesn't exist, add it and store it in the same variable.
Add the List<string> to the dictionary under the "somelanguage" key.
The code will look like this:
private Dictionary<string, List<string>> dictionary;
void AddCountries(string languageKey, List<string> coutriesToAdd)
{
List<string> existingValue = null;
if (!dictionary.TryGetValue(languageKey, out existingValue))
{
// Create if not exists in dictionary
existingValue = dictionary[languageKey] = new List<string>()
}
existingValue.AddRange(coutriesToAdd);
}
You simply need to check whether the value exists in the dictionary, like this:
if (!filters.ContainsKey("country"))
filters["country"] = new List<string>();
filters["country"].AddRange("your value");
Assuming you are trying to add value for key country
List<string> existingValues;
if (filters.TryGetValue(country, out existingValues))
existingValues.Add(value);
else
filters.Add(country, new List<string> { value })
If your values is List<string>
List<string> existingValues;
if (filters.TryGetValue(country, out existingValues))
existingValues.AddRange(values);
else
filters.Add(country, new List<string> { values })
Make use of IDictionary interface.
IDictionary dict = new Dictionary<String, List<String>>();
if (!dict.ContainsKey("key"))
dict["key"] = new List<string>();
filters["key"].Add("value");
i have a list where it is having dictionaries.now i want to retrive all values of dictionary how?
whenever i try to run a foreach in the list it doesnt show the type Dictionary in item.like
foreach(Dictionary dict in products)
i used to do it in java but i cant do it in C# why? and what will be the solution?
the code is given bellow
List<Dictionary<String,String>> products=new List<Dictionary<String,String>>();
products=loader.filterproductsbysubcat(subcat);
and here is the generated dictionary list
List<Dictionary<String, String>> productlist = new List<Dictionary<string, string>>();
String qry = "select product_tbl.Id,product_tbl.brandid,product_tbl.gender,product_tbl.info,product_tbl.name,product_tbl.price,product_tbl.productcode,product_tbl.status,image_tbl.imagename,image_tbl.imagepath from product_tbl left join image_tbl on product_tbl.Id=image_tbl.productid where product_tbl.subcat='"+subcategoryid+"'";
dt = db.ConnectDataBaseReturnDT(qry);
foreach (DataRow row in dt.Rows)
{
Dictionary<String, String> mydictionary = new Dictionary<string, string>();
mydictionary.Add("id",row["Id"].ToString());
mydictionary.Add("brandid", row["brandid"].ToString());
mydictionary.Add("gender", row["gender"].ToString());
mydictionary.Add("info", row["info"].ToString());
mydictionary.Add("name", row["name"].ToString());
mydictionary.Add("price", row["price"].ToString());
mydictionary.Add("productcode", row["productcode"].ToString());
mydictionary.Add("status", row["status"].ToString());
mydictionary.Add("imagename", row["imagename"].ToString());
mydictionary.Add("imagepath", row["imagepath"].ToString());
productlist.Add(mydictionary);
}
return productlist;
You need to specify the generic parameters:
foreach(Dictionary<string, string> dict in products)
C# does not have 'raw types' for generics like Java.
You can use:
foreach(var item in products)
{
var key = item.Key;
var value = item.Value;
}
I was wondering if it were possible to make a list from the dictionary values where the key is a specified value?
The dictionary would like this:
Sidcup - DPC1
Sidcup - DPC2
Blackheath - DPC3
Blackheath - DPC4
Bexleyheath - DPC5
In fact, I'm not entirely implementing a Dictionary as above is a good idea. Here is its implementation:
DataSet ds = EngineBllUtility.GetDPCsForImportFile(connectionString, fileID);
if (ds.Tables.Count > 0)
{
DataTable dtDPCs = EngineBllUtility.GetDPCsForImportFile(connectionString, fileID).Tables[0];
Dictionary<string, string> preliminaryList = new Dictionary<string, string>();
if (dtDPCs.Columns.Contains("DPCNumber") && dtDPCs.Columns.Contains("BranchName"))
foreach (DataRow dataRow in dtDPCs.Rows)
{
preliminaryList.Add(dataRow["BranchName"].ToString(), dataRow["DPCNumber"].ToString());
}
I have the following code: (Excuse the last line, its just so you have an idea of what I'm trying to do).
foreach (string branch in branchNames)
{
string subfolder = System.IO.Path.Combine(saveLocation, branch);
System.IO.Directory.CreateDirectory(subfolder);
List<string> certificateList = new List<string>();
certificateList.Add(DPCNumber in preliminaryList where Key = branch);
}
In the above the branch is the key from the Dictionary. I need to iterate through because it needs to create a new folder and then do something with the certificateList I am creating.
Sure:
private static void TestZip()
{
Dictionary<string, string> stringstringdic = new Dictionary<string, string>();
stringstringdic.Add("1", "One");
stringstringdic.Add("2", "Two");
stringstringdic.Add("3", "Three");
stringstringdic.Add("4", "Four");
stringstringdic = stringstringdic.Where(pair => pair.Key != "1")
.ToDictionary(pair => pair.Key, pair => pair.Value);
List<string> stringlist = stringstringdic.Keys.Concat(stringstringdic.Values).ToList();
foreach (string str in stringlist)
{
Console.WriteLine(str);
}
}
//Output:
//2
//3
//4
//Two
//Three
//Four
Of course, you'll have to change the Where clause to reflect your real need.
If I understood you right, it's like .Where(pair => pair.Key == branch)
If I understand you correctly you want to add the value based on a key to a separate List?
certificateList.Add(preliminaryList[branch])
This is simplified as I really need to see the declaration of preliminaryList to know how DPCNumber fits into all of it. Could it be...
certificateList.Add(preliminaryList[branch].ToString())
To simply create a list of keys you can do the following.
var dictionary = new Dictionary<string, string>();
dictionary.Add("key1", "value1");
dictionary.Add("key2", "value2");
dictionary.Add("key3", "value3");
dictionary.Add("key4", "value4");
dictionary.Add("key5", "value5");
var list = dictionary.Keys.ToList();
This should give you a list with values "key1", "key2", "key3", "key4", "key5".
You can put a where clause in to filter out certain keys. The following gives all keys which contain a "2" (random example), resulting in just "key2".
var filteredList = dictionary.Keys.Where(key => key.Contains("2")).ToList();
Edit:
To get a value given a specific key.
string value = dictionary["key1"];
Note, the key is a dictionary must be unique, so for a given key you will only ever get a single value back and not a list of values.