How to get the TValue List<> of Dictionary<> - c#

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

Related

Get Values from dictionary present in List

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

Checking all entries from one Dictionary are in another Dictionary

i have two Dictionarys A & B, i want to see if all entries in A exist in B. In the past i've compared Lists using the following:
var set1 = new HashSet<String>(list1);
var set2 = new HashSet<String>(list2);
return set1.SetEquals(set2);
What i have thought to do is simply loop over each value in Dictionary A using:
dictA.TryGetValue(dictBvalue, out item)
this will return null on the item var if the value isn't there, but this seems a little long winded.
Is there a quick and effcient way of comparing dictionaries?
Thanks.
You could use All extension and do this.
var allexist = list1.All(x=> list2.ContainsKey(x.Key) && list2[x.Key] == x.Value)
here is the solution if you want to loop over each value
Dictionary<string, string> dictA = new Dictionary<string, string>();
Dictionary<string, string> dictB = new Dictionary<string, string>();
bool allexist = true;
foreach (var itemA in dictA)
{
if (!dictB.ContainsKey(itemA.Key))
{
allexist = false;
}
}
Actually, you asked for a method comparing dictionaries but your code example refer to HashSet which is different.
For HashSets, you can use IsSubsetOf and SetEquals methods.
To compare dictionaries, you can use DictionaryEquals method from this answer

Merge two dictionaries and remove duplicate keys and sort by the value

I have to merge two dictionaries into one dictionary with removing duplicate entries and add if not present in the first dictionary.
Dictionary<int, string> firstDict = new Dictionary<int, string>();
firstDict.Add(1, "X");
firstDict.Add(2, "B");
Dictionary<int, string> secondDict = new Dictionary<int, string>();
secondDict.Add(1, "M");
secondDict.Add(4, "A");
Result Should be like this:
{4, "A"}
{2, "B"}
{1, "X"}
You can use Concat with sample LINQ to achieve what you want. Here it is:
Dictionary<int, string> result =
firstDict.Concat(secondDict.Where(kvp => !firstDict.ContainsKey(kvp.Key)))
.OrderBy(c=>c.Value)
.ToDictionary(c => c.Key, c => c.Value);
The result is:
{4, "A"}
{2, "B"}
{1, "X"}
You would do something like this:
var result = firstDict;
foreach(var newitem in secondDict.Where(x => !firstDict.ContainsKey(x.Key)))
result.Add(newItem);
var sortedResult = result.OrderBy(x => x.Value);
Please note that result is still a dictionary but unsorted while sortedResult is sorted but no longer a dictionary, because the order of items in a dictionary is undefined. You can't use SortedDictionary<TKey, TValue> either, because it is sorted by the key and not the value.
I would try this:
foreach(var pair in secondDict)
{
if(!(firstDict.ContainsKey(pair.Key)))
{
firstDict.Add(pair.Key, pair.Value);
}
}
Is this what you want? I havenĀ“t tested it yet by compiler, so give it a try.
Try this:
foreach (var item in firstDict)
{
secondDict[item.Key] = item.Value;
}
Update:
If you want to preserve initial values, make a copy of secondDict:
Dictionary<int, string> resultDict = new Dictionary<int, string>(secondDict);
foreach (var item in firstDict)
{
resultDict[item.Key] = item.Value;
}
foreach (int key in secondDict.Keys)
{
if (!firstDict.ContainsKey(key))
firstDict.Add(key, secondDict[key]);
}
I am not sure, do you want to merge both of them?
If so, can you just:
1st. Create a copy of the firstDict where the final results will be set.
2nd. For each key in secondDict:
1. Check if key exists in firstDict.
1.1. If it does exist(we want to keep the current result): do not do anything(sorry I miss read the result earlier)
1.2. If it doesn't exist then insert it as is(key-value from secondDict into firstDict)
Hopefully it helps!

SelectList with Dictionary, add values to the Dictionary after it's assigned to SelectList

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.

How to extract List<int> from Dictionary<int, string>?

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

Categories

Resources