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();
Related
I have a Dictionary<> that's set up as follows:
Dictionary<int, List<string>> srt = new Dictionary<int, List<string>>();
and I would like to access a specific string in the List<string> (which is the TValue in the Dictionary<>
).
For example -> Given: Dictionary<1, {"string1", "string2", "string3"}>, how can I access "string2", and only "string2" specifically.
I hope the question was clear enough to understand. If it wasn't, tell me what I need to clarify.
Thanks!
Is this what you want?
Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
dict .Add(1, new List<string> { "Hello", "World" });
string result = fileList[1][1]; //Will output "World"
try this:
var res = srt[1][0]; //"string1"
First index is a key and second index refers to list element
You can use this
var concreteValue = str.Values.SelectMany(l => l.Where(v => v.Equals("string2")))
.FirstOrDefault();
It's pretty simple actually. Access by key to the specific list then you can treat it as an array. The syntax would be srt[key][index]
Which means to access string2 specifically you need write as var b = srt[1][1]; here b will have string2
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.
Say I have two dictionaries:
Dictionary<string, string> orig = new Dictionary <string, string>();
orig.Add("one", "value one");
orig.Add("two", "");
orig.Add("three", "");
Dictionary<string, string> newDict = new Dictionary <string, string>();
newDict.Add("one", "this value should not be added");
newDict.Add("two", "value two");
newDict.Add("three", "value three");
How can I merge the two dictionaries so that the resulting dictionary updates the keys only where their corresponding values are empty? Additionally, the merge should not add any keys that are present in new but not in orig. That is, "one" still has the value "value one" while "two" and "three" are updated with the values from new.
I tried using orig.Concat(new);, but that leaves me with the original dictionary. Perhaps this can be done with LINQ?
Try:
orig = orig.Keys.ToDictionary(c => c, c=>(orig[c] == "" ? newDict[c] : orig[c]));
This loop does what you want efficiently and readable:
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (var keyVal in orig)
{
if (!string.IsNullOrEmpty(keyVal.Value))
result.Add(keyVal.Key, keyVal.Value);
else
{
string val2;
if (newDict.TryGetValue(keyVal.Key, out val2))
result.Add(keyVal.Key, val2);
else
result.Add(keyVal.Key, "");
}
}
Result:
one, value one
two, value two
three, value three
I would use the foreach
foreach (var pair in orig.Where(x=> string.IsNullOrEmpty(x.Value)).ToArray())
{
orig[pair.Key] = newone[pair.Key];
}
Extension method 'one-liners' are great when they help to clarify intention, but for something like this, I would be inclined to write a small method with an explicit loop that does the desired operation. I think this is much cleaner than creating a new dictionary using various extension method transformations:
public void PopulateMissingValues(Dictionary<string, string> orig, Dictionary<string, string> newDict)
{
foreach (var pair in orig.Where(p => p.Value == string.Empty))
{
string newValue;
if (newDict.TryGetValue(pair.Key, out newValue))
orig[pair.Key] = newValue;
}
}
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.
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.