Intersection of Dictionary based on keys and values - c#

I have a couple of dictionaries that I want to perform intersection on.
two dictionaries might have different lists of values for the same key.
Example:
Dictionary<int, List<int>> Primary = new Dictionary<int, List<int>>();
Primary.Add(1, new List<int>());
Primary[1].Add(5);
Primary[1].Add(6);
Primary[1].Add(7);
Primary.Add(2, new List<int>());
Primary[2].Add(5);
Dictionary<int, List<int>> Secondary = new Dictionary<int, List<int>>();
Secondary.Add(1, new List<int>());
Secondary[1].Add(6);
Secondary[1].Add(7);
Secondary[1].Add(8);
Secondary.Add(3, new List<int>());
Secondary[3].Add(5);
So I want the resultant dictionary to contain only:
[1],[list<6,7>]
How can I achieve this? The actual data structure where I want the intersection is of the form:
Dictionary<long, SortedList<int,List<long>>>

You can achieve this as follows:
var result = Primary.Keys.Intersect(Secondary.Keys)
.ToDictionary(key => key,
key => Primary[key].Intersect(Secondary[key]).ToList());
Transforming the result into Dictionary<long, SortedList<int,List<long>>> should be easy enough.

Related

How do I iterate over a hashset of dictionaries

Apologies in advance; I am on day 3 of trying to learn C#.
I am instructed to build a hashset of dictionaries; no problem. I see that that has been built. I now need to iterate over the hashset and copy the entries to a new list if the dictionary's key != a particular string. Could someone kindly explain the proper syntax for achieving this seemingly simple task?
var goodSongs = new List<Dictionary<string,string>>();
var allSongs = new HashSet<Dictionary<string, string>>();
Dictionary<string, string> meatloaf = new Dictionary<string, string>();
meatloaf.Add("Meatloaf", "Paradise By The Dashboard Light");
Dictionary<string, string> aerosmith = new Dictionary<string,string>();
aerosmith.Add("Aerosmith", "Cryin'");
Dictionary<string, string> nickelback = new Dictionary<string, string>();
nickelback.Add("Nickelback", "Rockstar");
allSongs.Add(nickelback);
allSongs.Add(aerosmith);
allSongs.Add(meatloaf);
//foreach loop to iterate dictionaries goes here
Goal - To get unstuck, hope to learn C#, and decide if I want to keep going down this rabbit hole. Thanks to all.
Here is an example of how to iterate through the hashset and then the dictionary:
var all = new HashSet<Dictionary<string, string>>();
Dictionary<string, string> newDict = new Dictionary<string, string>();
newDict.Add("M", "T");
all.Add(newDict);
foreach(Dictionary<string,string> dict in all)
{
foreach(KeyValuePair<string,string> pair in dict)
{
string key = pair.Key;
string value = pair.Value;
}
}

C# :- Loop over 4 Dictionaries

I've 4 Dictionaries like,
Dictionary<string, string> home = new Dictionary<string, string>();
Dictionary<string, string> home1 = new Dictionary<string, string>();
Dictionary<string, string> away1 = new Dictionary<string, string>();
Dictionary<string, string> away2= new Dictionary<string, string>();
now I want to perform Assert for each of them on their Keys and values. How should i do that ?
i was thinking to adding them as below,
var dic = new[] { home , home1 , away1 , away2};
and then use Switch but it seems difficult as switch can't be used on array. So how should i approach this one ?
Why don't you create a function for asserting a dictionary, then loop over the array and call it, something like this:
foreach (var element in dic)
{
AssertOnDictioanry(element);
}
Hope this was useful.

Get dictionary key if value contains string

I have this Dictionary:
static Dictionary<int, string> Players = new Dictionary<int, string>();
dictionary.Add(1, "Chris [GC]");
dictionary.Add(2, "John");
dictionary.Add(3, "Paul");
dictionary.Add(4, "Daniel [GC]");
I want to get the key of values that contains "[GC]"
Any idea how?
Thanks.
Use LINQ:
var result = Players.Where(p => p.Value.Contains("[GC]")).Select(p => p.Key);
Use a query like below.
var itemsWithGC = dictionary.Where(d => d.Value.Contains("[GC]")).Select(d => d.Key).ToList();
foreach (var i in itemsWithGC)
{
Console.WriteLine(i);
}
Actually there's a more performant way of solving this issue, but it might require some refactor...
Whenever you add a new player containing "[GC]", you can fill a HashSet<int>:
Dictionary<int, string> Players = new Dictionary<int, string>();
HashSet<int> gcPlayers = new HashSet<int>();
dictionary.Add(1, "Chris [GC]");
gcPlayers.Add(1);
dictionary.Add(2, "John");
dictionary.Add(3, "Paul");
dictionary.Add(4, "Daniel [GC]");
gcPlayers.Add(4);
So now getting all keys which have "[GC]" is as easy as using the whole set called gcPlayers.
This will avoid a query and iterate the entire dictionary to get all coincidences, while you'll avoid adding duplicates to gcPlayers because it's a set (i.e. an unordered collection of unique values).

2-dimensional array with duplicated index key

i want to translate this line of code from php to asp.net
$subid[$value['parentid']][] = $value['id'];
i'm not familiar with asp.net data structure, i've tried arraylist but can't insert at [1], dictionary do not allow duplicated keys, anyone have ideas?
thanks
I'm not familiar with PHP (anymore) and SO is not a translation service, but you can use
List<Tuple<int, int>>
or
Lookup<int, int>
instead (assuming that your ids are ints).
var list = new List<Tuple<int, int>>();
list.Add(Tuple.Create(1, 1));
list.Add(Tuple.Create(1, 2));
list.Add(Tuple.Create(2, 3));
list.Add(Tuple.Create(2, 4));
list.Add(Tuple.Create(3, 5));
With Enumerable.ToLookup you can create a Lookup.
var lookup = list.ToLookup(t => t.Item1, t => t.Item2);
Find all products with parent-id = 1:
var parentID1 = lookup[1];
foreach (var value in parentID1)
Console.Write(value);
You can use a Dictionary with a little tweak to achieve what you want.
You create a dicionary like this:
Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
You add items to it like:
if(myDictionary.ContainsKey("myKey")) myDictionary["myKey"].Add("myItem");
else
{
myDictionary.Add("myKey", new List<string>(){"myItem"});
}
If you ask for a certain key, it will return a reference to the list with all related items.

Create an int[] from Dictionary<int, List<int>>, from each dictionary element's Value List<int> I need an array which contains all dictionary elements

The solution I have for now is as...
Dictionary<int, List<int>> oDict = <Some code to fill in the dictionary>;
var oList = new List<int>();
oDict.Values.ForEach(oList.AddRange);
oList.ToArray();
Is there a way to do this without using the additional List<int>?
Yup, that looks like:
var array = oDict.Values.SelectMany(list => list).ToArray();
(If you only want distinct elements, just call Distinct before ToArray.)

Categories