I would like to create an extension method that will allow me to call ToSerializableDictionary(p => p.ID) instead of .ToDictionary(p => p.ID) in the following LINQ context. Though I'm not sure what class i'm supposed to be making an extension method for to replace ToDictionary<T>.
response.attributes = (
from granuleGroup in groups
let granuleRow = granuleGroup.First().First()
select new USDAttributes()
{
id = (int)granuleRow["id"],
...
attributes =
(
...
).ToDictionary(p => p.ID) <--** LINE IN QUESTION **
}
).ToList();
My SerializableDictionary class taken from here is so that I may serialize dictionary objects in my webservice to return hash tables that play nice with JSON.
Initially I was creating an extension method for IDictionary so I can do something like this: ...).ToDictionary(p => p.ID).ToSerializableDictionary(); But this has been a complete failure because it's my first time creating extension methods and I don't know what I'm doing.
public static class CollectionExtensions
{
public static SerializableDictionary<string, object> ToSerializableDictionary(this IDictionary<string,object> sequence)
{
SerializableDictionary<string, object> sDic = new SerializableDictionary<string, object>();
foreach (var item in sequence)
{
}
return sDic;
}
}
public static SerializableDictionary<TKey, T> ToSerializableDictionary<TKey, T>(this IEnumerable<T> seq, Func<T, TKey> keySelector)
{
var dict = new SerializableDictionary<TKey, T>();
foreach(T item in seq)
{
TKey key = keySelector(item);
dict.Add(key, item);
}
return dict;
}
Actually the class you provided has a handy constructor for doing this, so you can actually do
attributes = new SerializableDictionary( (
...
).ToDictionary(p => p.ID) );
But here you go with the extension method (again using that constructor):
public static partial class Extension {
public static SerializableDictionary<T, Q> ToSerializableDictionary(
this IDictionary<T, Q> d) {
return new SerializableDictionary(d);
}
}
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