c# loop through dictionary passed through session - c#

I created and added items to this dictionary and set it to session. Now I'm trying to retrieve the session in another page and loop through the dictionary, how do I do so? I tried using foreach loop but the membersDictionary variable seems to be not a dictionary, how do I loop through the dictionary passed to session? Please help, thanks.
Home.aspx.cs
Dictionary<string, string> membersDictionary = new Dictionary<string, string>();
membersDictionary.Add(TB_member1Username.Text, TB_member1mobile.Text);
membersDictionary.Add(TB_member2Username.Text, TB_member2mobile.Text);
Session["FamPlanMembersDict"] = membersDictionary;
Home2.aspx.cs
var membersDictionary = Session["FamPlanMembersDict"];
foreach(var item in membersDictionary)
{
.....
}

Cast it as a dictionary of two strings as follows:
Dictionary<string, string> membersDictionary = Session["session_values"] as Dictionary<string, string>;
foreach(var item in membersDictionary)
{
.....
}

One way would be to cast it
var membersDictionary = (Dictionary<string, string>)Session["FamPlanMembersDict"];
foreach(var item in membersDictionary)
{
.....
}
Though quite old the documentation also states the same. The Session output is object as we wanted to be able to save everything there.

Related

Populating a two dimensional array is adding a new element instead of a row

I have a large tab delimited text file that I need to parse.
This is a sample of the data as it looks in notepad++:
Here is my code:
private IEnumerable<string> ParsePriceFile()
{
var priceFile = Path.Combine(Settings.Default.WatchDirectory, Settings.Default.CustomerPricingDataFile);
var priceFileList = new List<string>();
foreach (var line in File.ReadLines(priceFile))
{
priceFileList.AddRange(line.Split('\t'));
}
return priceFileList;
}
I'm ending up with these results though:
I can just count each element and reference it with the appropriate index but I thought I could make a 2d array. What am I doing wrong?
You can use new List<string[]>() and then add each entire array to it:
var priceFileList = new List<string[]>();
foreach (var line in File.ReadLines(priceFile))
{
priceFileList.Add(line.Split('\t'));
}
The result is not literally a 2D array, but a List of 1D arrays instead. For many purposes this will not make much difference.
You are using AddRange on a List, which simply adds the IEnumerable passed in to the end of the list. If you want two values for each item, you'll have to make your List something that will hold that, like a Dictionary<string, string> or a List<<Tuple<string, string>
var priceFileList = new Dictionary<string, string>();
foreach (var line in File.ReadLines(priceFile))
{
priceFileList.Add(line.Split('\t')[0], line.Split('\t')[1]);
}

Need to create a custom object by looping the list in c# is it possible

I need to create a list object based on a list of key-value pair dynamically but I can't assign the key value in object by looping the list.
foreach (KeyValuePair<string, IEnumerable<string>> item in List)
{
string keyValue = item.Key.ToString();
object value = new { item.Key = item.Value };
somefunction(value);
}
the item.key will throw issue. Any suggestions for how to create an object while looping through the list.
For example if the item value is { key: "sampleKey" , value : "sampleValue"} i need to create an object as { "sampleKey" = "sampleValue" }. How can I achive this.
I believe the answer is IEnumerable<string> newList = item.Value; instead of object value = new { item.Key = item.Value };
You could do something with the dynamic keyword and the ExpandoObject (https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-5.0), but if you're keys are so dynamic, I don't see a point of having them in a class/object at all. Rather store the data as a dictionary, which will then let you retreive data from strings as well.

How to get a values list from a dictionary where the key matches in a list in c#

I have a dictionary and I want to retrieve all the values list from the dictionary based on a condition on the key, i.e. I want to retrieve only the values for which the respective key matches in alist.
Example: dictionary is as follows
IDictionary<string, string> maskingValues = new Dictionary<string, string>();
maskingValues.Add("cat", "Me#ena");
maskingValues.Add("dog", "N&avya");
maskingValues.Add("llama", "vivek!a");
maskingValues.Add("iguana", "sh^ams");
and I have list of strings as
List<string> keysString = new List<string>();
keysString.Add("cat");
keysString.Add("fox");
Now my requirement is to get the values list from the dictionary where the key matches from the keysString list.
The output should be
Me#ena
till now what I have done is
var all_parameters = maskingValues .Keys.ToList();
var parameters_to_mask = all_parameters.Intersect(keysString);
var values_list = parameters_to_mask.Where(k => data_dictionary.ContainsKey(k)).Select(k => data_dictionary[k]);
so values_list will contain the output Me#ena, I retrieved all the keys from the dictionary and then compared the keys list with the keysString list and then retrieved the values list from the output of the two list's intersect. But can I do it in more optimized way so that the code and the performance is good.
Thanks in advance. Please help me out.
This should work:
var q = maskingValues.Where(x => keysString.Contains(x.Key)).Select(x => x.Value);
foreach (var item in q)
{
Console.WriteLine(item);
}
There are a lot of solutions. This one for example:
var newlist = maskingValues.Where(x => keysString.Contains(x.Key)).Select(y=>y.Value).ToList();
I came up with a quick bit of code to do this fully using linq.
keysString.Where(x => maskingValues.Keys.Contains(x)).ToList().ForEach(x => Console.WriteLine(maskingValues[x]));
Not sure I got the spec right but this is faster than linq:
var matches = new List<string>();
foreach (var key in keysString)
{
if (maskingValues.TryGetValue(key, out string value))
{
matches.Add(value);
}
}
If your dictionary is large, you can improve performance by taking advantage of the fact that accessing an element by key in a dictionary is O(
var result = keysString
.Select(k =>
{ string value;
maskingValues.TryGetValue(k, out value);
return value;
})
.Where(v => v != null);
... etc ...
Note that using TryGetValue is more efficient than calling Contains then the dictionary indexer.
This Should Work:
Below Solution is used when you know your Key name and want to retrive value of key
string objectValue;
maskingValues.TryGetValue("cat", out objectValue);
If you want to Retrive All values from Dictionary than used single line of code: maskingValues.Values

Get all Keys from a MultiDictionary

Im looking for a way to get all FIRST level Keys of a multiDictionary and im totaly unable to get them (its for debugging purpose)
i declared the dictionary like this :
private Dictionary<string, Dictionary<string, Packet>> PacketsStore = new Dictionary<string, Dictionary<string, Packet>>();
So how can i print out a list of all the base keys?
how could i then print out the second level keys incase i need it too later...
thanks in advance!
First level, the well-known way:
var allKeys = PacketsStore.Keys;
Sub-dictionary keys, the LINQ way:
var allSubKeys = PacketsStore.SelectMany(pair => pair.Value.Keys);
OP has commented out on other answer that the two nested foreach loops were more suitable for debugging purposes, but, after all, if OP wants to output all subkeys to console, it can still be done with a one-liner solution:
// One-liner solution!
PacketsStore.SelectMany(pair => pair.Value.Keys).ToList().ForEach(Console.WriteLine);
foreach(KeyValuePair<string, Dictionary<string, Packet>> entry in PacketsStore)
{
string key = entry.Key; // first level
foreach(KeyValuePair<string, Packet> entryInner in entry.Value)
{
string keyInner = entryInner.Key // second level
}
}
I have taken keys into variables you can take the same into some collection. Purpose was to get keys :)
For all keys, try:
var keys = PacketsStore.Keys.ToArray();
and for second level keys:
List<string> secondaryKeys;
foreach (var key in keys)
{
secondaryKeys.AddRange(PacketStore[key].Keys.ToArray());
}

Grouping Items In A List View

I have a Dictionary that is declared thusly:
Dictionary myDictionary<string, List<FCPort>> = new Dictionary<string, List<FCPort>>();
the key is a string representing a switch name. The value is a list of port objects for that switch. I am trying to add the items in the Dictionary to a ListView with this code:
foreach (KeyValuePair<string, List<FCPort>> portpair in results)
{
ListViewItem item1 = new ListViewItem(portpair.Key);
foreach (FCPort port in portpair.Value)
{
item1.SubItems.Add(port.FCIDList[0]);
item1.SubItems.Add(port.WWPNList[0]);
item1.SubItems.Add(port.TextSerializePortName());
this.ResultsListView.Items.Add(item1);
}
}
However, I get a run-time error basically saying that I have a duplicate item in the list. That makes sense. I am attempting to group by the dictinoary key (the switch name). Is there a way to somehow group the items in the listview, or dynamically add Listviews to the GroupBox on the fly? Basically add a new ListView for each key in the Dictionary? I am still learning C# and forms are still new.
you could use LINQ lookup to group by your key selector.
and extend your portpair to enumerable when add to into listview subitems
This is the code snippet I did sometimes hopefully could help you.
Dictionary<String, Country> dict = new Dictionary<string, Country>();
dict.Add("Toronto", Country.Canada);
dict.Add("New York", Country.US);
dict.Add("Vancover", Country.Canada);
dict.Add("Seattle", Country.US);
dict.Add("Fredericton", Country.Canada);
Lookup<Country,String> lookup = (Lookup<Country,String>) dict.ToLookup(pair =>pair.Value, pair => pair.Key);
foreach (var countryGroup in lookup)
{
item = new ListViewItem(countryGroup.Key.ToString());
item.SubItems.Add(string.Format("{0}", string.Join(",", countryGroup.Select(s => "#" + s))));
lv.Items.Add(item);
item = null;
}

Categories