While my program is running it receives messages with Id's and data in one message.
I want to make a new List for every Id where I can store the data from that Id.
The problem is that I don't know how many Id's I wil receive until my program is running. The only thing I know is that it's a lot. So I don't know if it is possible or how I should do this.
This is wat I'm basically trying to do:
if (!(idlist.Contains(id))){
idlist.Add(id);
List<string> id.ToString() = new List<string>();}
Use Dictionary:
var myDictionary = new Dictionary<int, List<string>>();
// .....
List<string> myList;
myDictionary.TryGetValue( id, out myList );
if ( null == myList ) {
myList = new List<string>();
myDictionary[id] = myList;
}
myList.Add( "hello world" );
You can do something like:
Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>();
dictionary[newId] = new List<string>();
dictionary[newId].add("Hello!");
Dictionaries are quite handy!
You can do something like this as well:
if(!dictionary.ContainsKey(newId)){
//Add the new List<string> to the dictionary
}else{
//Add to the existing List<string> at dictionary[newId]
}
Hope this helps!
You can use Dictionary that can store a list of Key-Value-Pairs. Your key would be the id and the value would be the list of strings.
Dictionary<int,List<string>> ids = new Dictionary<int,List<string>>();
And when you get an ID you create a new entry like this:
ids[id] = new List<string>();
If the dictionary already contained a entry for this ID it will be overwritten. You can check using ContainsKey to prevent that:
if(!ids.ContainsKey(id))
{
ids[id] = new List<string>();
}
I dont believe you can create a list the way you are attempting. What you might like to try is something like this:
IDictionary<int, List<string>> idDictionary = new Dictionary<int, List<string>>()
//wait for messages
...
//handle new message
if (!idDictionary.containsKey(incommingId)){
idDictionary.add(incommingId, new List<String>())
}
idDictionary[incommingId].add(data);
Using a dictionary to hold the data lists for all received id's should provide decent lookup performance. However this may change if you receive many hundreds of different id's when the program is running.
Related
I'm trying to do something like this:
Dictionary dict = Dictionary<string, List<string>>();
dict.Add("someKey1", new List<string>());
dict.Add("orange", new List<string>());
dict.Add("foo", new List<string>());
And then when I iterate over the keys, I'd like them to have retained the order as they were added:
foreach(KeyValuePair<string, string> entry in myDictionary)
{
Console.WriteLine(entry.Key);
}
Should print out:
someKey1
orange
foo
I know that c# Dictionary keys don't retain their order as they were added, so is there another way I can do this so that the keys retain their order?
A generic ordered dictionary does not exist in .NET, but you could use the OrderedDictionary class instead. See MSDN
Use Queue class from System.Collections.Generic to ensure the order.
// Create queue
Queue<TestItem> queue = new Queue<TestItem>();
// Add item
queue.Enqueue(new TestItem { });
// Fetch item
queue.Dequeue();
I have a list like,
List<string> list = new List<string>();
list.Add("MEASUREMENT");
list.Add("TEST");
I have a dictionary like,
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("BPGA", "TEST");
dict.Add("PPPP", "TEST");
dict.Add("RM_1000", "MEASUREMENT");
dict.Add("RM_2000", "MEASUREMENT");
dict.Add("CDMA", "TEST");
dict.Add("X100", "XXX");
Now, I want to get all matched data from dictionary based on list.
Means, all data from list match with dict value then get new dictionary with following mathched values
Is there any way to achieve this by using lambda expression?
I want result like this.
Key Value
"BPGA", "TEST"
"PPPP", "TEST"
"RM_1000", "MEASUREMENT"
"RM_2000", "MEASUREMENT"
"CDMA", "TEST"
Thanks in advance!
You should be using the dictionary like it is intended to be used i.e. a common key with multiple values for example:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
Then all you need to do when adding the values is:
dict.Add("TEST", new List<string>() { /*strings go in here*/ });
Then to get all the results from a key like:
List<string> testValues = dict["TEST"];
To make it safe however you should check that the key exists i.e.
if (dict.ContainsKey("TEST"))
{
//Get the values
}
Then to add values to a current key you go do something like:
dict["TEST"].Add("NewValue");
If you insist on keeping the same structure, although I do not recommend it, something like the following will work:
List<string> testKeys = new List<string>();
foreach (var pairs in dict)
{
if (pair.Value == "TEST")
{
testKeys.Add(pair.Key);
}
}
Or even the following LINQ statement:
List<string> testKeys = dict.Where(p => p.Value == "TEST").Select(p => p.Key).ToList();
For a generic query to find the ones from your list use:
List<string> values = dict.Where(p => list.Contains(p.Value)).ToList();
I am getting this error because I have a duplicate key in the SortedList.
Item has already been added. Key in dictionary: 'V22.1' Key being added: 'V22.1'
BUT the value of these duplicate keys are different. So I am thinking of adding another object before the preceding the duplicate key in order to find its value. I was thinking of putting SortedList within a SortedList. An illustration for my intention for example:
(key)"ICD9" : (key)"V22.1" : (value)"Supervision of other normal pregnancy"
(key)"ICD10" : (key)"V22.1" : (value)"Motorcycle passenger injured in collision with two- or three-wheeled motor vehicle in nontraffic accident"
I hope that makes sense. I was thinking of doing something like this:
SortedList<string, SortedList<string, string>> slCodes;
slCodes = new SortedList<string, SortedList<string, string>>();
But the part I am stuck now is how do I add into the SortedList within the SortedList? I am stuck here:
strDesc = tbDesc.Text.Trim();
tblCodes = new DataTable();
GetCodesByDescription(strDesc, ref tblCodes); //<--This queries from database
DataView dvCodes = new DataView(tblCodes);
dvCodes.RowFilter = "CodeType='ICD10' OR CodeType='ICD9'";
foreach(DataRowView drv in dvCodes)
{
slCodes.Add(drv["Code"].ToString().Trim(), //<--Throws error here.
drv["Description"].ToString().Trim());
}
This is currently where I am stuck at on adding into the SortedList within a SortedList. I'm not even sure if this approach to having a key-value pair within a key is correct. Please help.
You need to first check the code type to determine which sub list to add to and if you need to create a new sub list.
foreach(DataRowView drv in dvCodes)
{
var codeType = drv["CodeType"].ToString().Trim();
var code = drv["Code"].ToString().Trim();
var description = drv["Description"].ToString().Trim();
if(slCodes.ContainsKey(codeType))
{
slCodes[codeType].Add(code, description);
}
else
{
var subList = new SortedList<string, string>();
subList.Add(code, description);
slCodes.Add(codeType, subList);
}
}
Alternatively since you only pull ICD9 and ICD10 codes you could prepopulate the two sub lists
var slCodes = new SortedList<string, SortedList<string, string>>();
slCodes.Add("ICD9", new SortedList<string, string>());
slCodes.Add("ICD10", new SortedList<string, string>());
dvCodes.RowFilter = "CodeType='ICD10' OR CodeType='ICD9'";
foreach(DataRowView drv in dvCodes)
{
var codeType = drv["CodeType"].ToString().Trim();
var code = drv["Code"].ToString().Trim();
var description = drv["Description"].ToString().Trim();
slCodes[codeType].Add(code, description);
}
slCodes is a SortedList object containing strings for keys and SortedList <string, string> for values, but you are not adding these types to it; rather 2 string objects.
You need to add a string and a SortedList <string, string>, instead of 2 string objects.
If you want to add something to an existing sorted list in slCodes, then you must first look up said list before adding 2 strings to it.
I have a the following code -
Dictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("keyA", "valueA");
myDict.Add("keyB", "valueB");
IEnumerable<SelectListItem> mySelectList = new SelectList(myDict, "key", "value")
Further down in the program, I want to add values to myDict. Is that possible? If yes, then how?
I want to do something like -
mySelectList.myDict.Add("keyC", "valueC");
If you're wanting to add items to myDict, this is certainly possible, and any changes will be reflected in any of mySelectList's enumerations as long as the changes are made before the enumeration (e.g. using .ToList()) is generated.
As a worked example:
Dictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("keyA", "valueA");
myDict.Add("keyB", "valueB");
IEnumerable<SelectListItem> mySelectList = new SelectList(myDict, "key", "value");
myDict.Add("keyC", "valueC");
var result = mySelectList.ToList();
// result is now a list containing three items - keyA, keyB and keyC.
myDict.Add("keyD", "valueD");
var result2 = mySelectList.ToList();
// result2 is a list containing four items. result is
// unchanged, containing just the original three.
Try something horrendous like this:
((Dictionary<string, string>)mySelectList.Items).Add("keyC", "valueC");
It would be better if you just kept the reference to myDict around in your own code, though, rather than abusing their property.
Note: It's very possible this doesn't work. I haven't tried it.
I have a method that takes a List<int>, which is a list of IDs. The source of my data is a Dictionary<int, string> where the integers are what I want a list of. Is there a better way to get this than the following code?
var list = new List<int>();
foreach (var kvp in myDictionary)
{
list.Add(pair.Key);
}
ExecuteMyMethod(list);
You could do
var list = myDictionary.Keys.ToList();
Or
var list = myDictionary.Select(kvp => kvp.Key).ToList();
Yes, you can use the Keys collection in the constructor of the list:
List<int> list = new List<int>(myDictionary.Keys);
Like Guffa said that's some thing which is easy and elegant.
or
List<int> nList = myDictionary.Keys.ToList<int>();