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");
Related
I have the following declaration and I need to get the first element from the list using key. Then after assigning that value to some variable again I need to remove that value alone from that list.
Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
For Example:
List<string> teamMembers = new List<string>();
teamMembers.Add("Country1Player1");
teamMembers.Add("Country1Player2");
teamMembers.Add("Country1Player3");
data.Add("Country1",teamMembers);
teamMembers = new List<string>();
teamMembers.Add("Country2Player1");
teamMembers.Add("Country2Player2");
teamMembers.Add("Country2Player3");
data.Add("Country2",teamMembers);
From the above dictionary, I need to select the Country1 's first element Country1Player1 and assign to some variable. After that I need to remove that value alone from the value list.
Expected output:
If I pass key as 'Country1' then it should give me Country1Player1 and that value needs to be removed the data dictionary. Key Country1 should contain only Country1Player2 & Country1Player3 in the list of values.
string firstTeamMember = null;
if (data.TryGetValue("Country1", out List<string> list) && list?.Any() == true)
{
firstTeamMember = list[0];
list.RemoveAt(0);
}
You could try sth like this:
if(data.TryGetValue("Country1", out var values))
{
var firstValue = values?.FirstOrDefault();
data["Country1"] = data["Country1"]?.Skip(1).ToList();
}
I have a list of files, and the filenames for those files contain some characters then an underscore, then anything else like so:
test_123.txt
What I'm trying to do is loop through these files, pull out the 'prefix' (the characters up to but not including the _, add the prefix to a list if it's not already in the list, and then add the whole filename as an element of that prefix.
That might be confusing so here's an example:
List of file names:
A_ieie.txt
B_ldld.txt
C_test.txt
A_232.txt
B_file2.txt
C_345.txt
So I am looping through these files and get the prefix like so:
string prefix = fileName.Substring(0, fileName.IndexOf('_'));
Now, I check if that prefix is already in a list of prefixes, and if not, add it:
List<string> prefixes = new List<string>();
if (!prefixes.Contains(prefix))
{
prefixes.Add(prefix);
}
So here's the prefixes that would be added to that list:
A //not yet seen, add it to list
B //not yet seen, add it to list
C //not yet seen, add it to list
A //already seen, don't add
B //already seen, don't add
C //already seen, don't add
Okay the above is easy to do, but what about when I want to add the filenames that share a prefix to a list?
Since these are going to be dynamically added and could be anything, I can't make several lists before hand. I thought about have a List of lists, but is that really the best way to do this? Would a class be ideal?
The end goal of the above example would be something like :
[0][0] = A_ieie.txt //This is the 'A' list
[0][1] = A_232.txt
[1][0] = B_ldld.txt //This is the 'B' list
[1][1] = B_file2.txt
[2][0] = C_test.txt //This is the 'C' list
[2][1] = C_345.txt
Sounds like you want a Dictionary:
var list = new Dictionary<string, List<string>>();
The Key would be the "prefix" and the Value would be a list of strings (the filenames).
EDIT
If you want the list of filenames to be unique, perhaps a HashSet is a better option:
var list = new Dictionary<string, HashSet<string>>();
Sounds like you want a Dictionary>
Then, each list is referenced by a key integer (or use a string to "name" the list):
public Dictionary<string, List<string>> myBookList = new Dictionary<string, List<string>>();
private void addList(string listName, List<string> contents)
{
myBookList.Add(listName, contents);
//direct add
List<string> science_Fiction_Books = new List<string>();
myBookList.Add("Science Fiction", science_Fiction_Books);
myBookList["Science_Fiction"].Add("mytitle.txt");
myBookList["Science_Fiction"][0] = "My book title.txt";
string fileLocation = #"c:\mydirectory\mylists\myBookTitle.txt";
myBookList["Science_Fiction"].Add(System.IO.Path.GetFileName(fileLocation));
//etc.
}
You can use linq to achieve this.
List<string> List = new List<string>() { "A_ieie.txt", "B_ldld.txt", "C_test.txt", "A_232.txt", "B_file2.txt", "C_345.txt" };
Dictionary<string, List<string>> Dict = new Dictionary<string, List<string>>();
Dict = List.GroupBy(x => x.Split('_')[0]).ToDictionary(x => x.Key, x => x.ToList());
How about this:
var textFileNameList =
new List<string>{"A_ieie.txt","B_ldld.txt","C_test.txt",
"A_232.txt","B_file2.txt","C_345.txt"};
var groupedList = textFileNameList.GroupBy(t => t.Split('_')[0])
.Select( t=> new {
Prefix = t.Key,
Files = t.Select( file=> file).ToList()
}).ToList();
I am trying to iterate a file reading data line by line. After reading I would like to store in Dictionary. keys are unique but values are having list of values for a key(may be 50 values per key). But while iterating keys comes randomly.How do I create a newlist for each key and store the value in the corresponding List when next time same key comes...how to store all those new keys and corresponding lists in dictionary.Please me on this..
Here is explanation of my code ..
Dictionary<String,List<PropertyCollection>> dict = new Dictionary<String,List<PropertyCollection>>();
List<String> list1 = new List<String>();
//Here I am iterating the each record and getting the type and id
for (i=1;i<datarr.length -1;i++){
String type = datarr[3].Trim();
String id = datarr[1].Trim();
//here I am checking the key in map adding
if(dict.ContainsKey(type)){
//I need help here if the key is not there create a new record with key as "type" and values as "id"s. All the values of same type should add in a list.If any new type comes in iteration it should add as new entry and having key and values are Ids in a list format.
I stuck here ..
}
}
I don't know how many "types " are there in that file .So I need to build the List dynamically.
Please help .
this is a pretty common scenario when working with a Dictionary whose value is a collection. You just need to make sure that the collection is initialized for that key before trying to add anything to it:
//using Dictionary<int, List<string>>
for(int i in ...)
{
if (!dict.ContainsKey(i))
dict[i] = new List<string>();
dict[i].Add("hello");
}
Now every new key coming in will get a fresh List<string>
Class to Build your data:
class DataBuilder
{
public Dictionary<string, List<string>> Data { get; } = new Dictionary<string, List<string>>();
public void Add(string key, string dataVal)
{
if (!Data.ContainsKey(key))
{
Data.Add(key, new BaseList<string>());
}
Data[key].Add(dataVal);
}
}
This is how you can use above class to build data while you are reading file(s):
static void Main(string[] args)
{
var builder = new DataBuilder();
builder.Add("Key1", "Test Data 1");
builder.Add("Key1", "Test Data 2");
builder.Add("Key2", "Test Data 3");
builder.Add("Key1", "Test Data 4");
}
Update as per your query: Change your code to this:
private void Process()
{
Dictionary<String, List<string>> dict = new Dictionary<String, List<string>>();
for (int i = 0; i < numOfRec - 1; i++)
{
//Code to Read record at index i into dataarr.
String type = datarr[3].Trim();
String id = datarr[1].Trim();
if (!dict.ContainsKey(type))
{
dict.Add(type, new BaseList<string>());
}
dict[type].Add(id);
}
}
}
In a dictionary, I want to add a list of numbers for a given key.But I am unable to do it.
for(int i = 0 ; i < size ; i++){
string input = Console.ReadLine();
string[] inputList = input.Split(' ');
count[Convert.ToInt32(inputList[0])]++;
if(!map.ContainsKey(Convert.ToInt32(inputList[0]))){
map.Add(Convert.ToInt32(inputList[0]),new List<string>());
map_index.Add(Convert.ToInt32(inputList[0]),new List<int>());
}
}
The question is bit unclear. My understanding of your problem is as follows: You have a dictionary, a value of the dictionary is a list, and you have trouble adding an item to that list. Since you didn't explain your notation I'm using more general names, just to give you an idea what has to be done:
Dictionary<int, List<string>> myDict = new Dictionary<int, List<string>>();
if (myDict.ContainsKey(myKey))
{
myDict[myKey].Add(myVal);
}
else
{
myDict[myKey] = new List<string> { myVal };
}
If the key is not in the dictionary you create an entry together with the list and initialize the list with the new value. If the key is there you just access the list (by using myDict[myKey]) and add the new value to the list. Since the list is always created for a new key you don't have to worry that it's not initialized when adding a value for an existing key.
This could be one the efficient Solution and much easier than if-else.
Dictionary<int, List<string>> myDict = new Dictionary<int, List<string>>();
try
{
myDict[myKey].Add(myVal);
}
catch
{
myDict[myKey] = new List<string> { myVal };
}
There is a 'one-command-line' way to do this using AddOrUpdate from ConcurrentDictionary:
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
...
var dictionary = new ConcurrentDictionary<int, string[]>();
var itemToAdd = "item to add to key-list";
dictionary.AddOrUpdate(1, new[]{item1ToAdd}, (key, list) => list.Append(itemToAdd));
// If key 1 doesn't exist, creates it with a list containing itemToAdd as value
// If key 1 exists, adds item to already existent list (third parameter)
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.