I want to list all extras (and their values) of an Intent object and save them in a dictionary.
The first problem is I don't necessary know all the keys. The second problem is that some values are strings, some are boolean... and so on. How could I get the values in a loop (looping through the keys) and save the value in C# Xamarin.Android?
LINQ variant
Bundle bundle = intent.Extras;
Dictionary<string, object> dict = bundle.KeySet()
.ToDictionary<string, string, object>(key => key, key => bundle.Get(key));
You could make this a convenient extension method as well:
public static Dictionary<string, string> ToDictionary(this Bundle bundle)
{
var dictionary = new Dictionary<string, string>();
foreach (var key in bundle.KeySet())
{
dictionary.Add(key, b.Get(key).ToString());
}
return dictionary;
}
Here what I found after a while and I'm going to share it so that someone else can save time.
//Didactic version
Bundle b = myIntent.Extras; //Where myIntent is of course an Intent
ICollection<string> c = b.KeySet(); //This is the collection of extras
Dictionary<string, string> d = new Dictionary<string, string>();
foreach (var key in c)
{
Object value = b.Get(key);
d.Add(key, value.ToString());
}
//Short version
var b = myIntent.Extras;
var d = new Dictionary<string, string>();
foreach (var key in b.KeySet();)
{
d.Add(key, b.Get(key).ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With