Using Extension methods to build new collection C# with Example



Using Extension methods to build new collection C# with Example

types (e.g. DictList) 
You can create extension methods to improve usability for nested collections like a Dictionary with a List 
value. 
Consider the following extension methods: 
public static class DictListExtensions 
{ 
public static void Add(this Dictionary dict, TKey 
key, TValue value) 
where TCollection : ICollection, new() 
{ 
TCollection list; 
 

if (!dict.TryGetValue(key, out list)) 
{ 
list = new TCollection(); 
dict.Add(key, list); 
} 
list.Add(value); 
} 
public static bool Remove(this Dictionary dict, 
TKey key, TValue value) 
where TCollection : ICollection 
{ 
TCollection list; 
if (!dict.TryGetValue(key, out list)) 
{ 
return false; 
} 
var ret = list.Remove(value); 
if (list.Count == 0) 
{ 
dict.Remove(key); 
} 
return ret; 
} 
} 
you can use the extension methods as follows: 
var dictList = new Dictionary>(); 
dictList.Add("example", 5); 
dictList.Add("example", 10); 
dictList.Add("example", 15); 
Console.WriteLine(String.Join(", ", dictList["example"])); // 5, 10, 15 
dictList.Remove("example", 5); 
dictList.Remove("example", 10); 
Console.WriteLine(String.Join(", ", dictList["example"])); // 15 
dictList.Remove("example", 15); 
Console.WriteLine(dictList.ContainsKey("example")); // False 
View Demo 

0 Comment's

Comment Form

Submit Comment