Created
April 7, 2017 15:33
-
-
Save tingwei628/aebef354f89590b2cdb7c96000130ab7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
問題: 一個陣列裡面的物件要怎麼過濾出相同的key value? | |
例如: var array = [{a:1, b:1}, {a:1, b:2}, {a:2, b:1}, {a:1, b:1}]; | |
(同時考慮 a, b的值) | |
*/ | |
// by @Hao Yu Liao | |
public class MultiKeyDictionary<K1, K2, V> | |
{ | |
private Dictionary<K1, Dictionary<K2, V>> baseDictionary = new Dictionary<K1, Dictionary<K2, V>>(); | |
public IEnumerable<V> Values { get { return baseDictionary.Values.SelectMany(e => e.Values); } } | |
public V this[K1 key1, K2 key2] | |
{ | |
get | |
{ | |
return baseDictionary[key1][key2]; | |
} | |
set | |
{ | |
baseDictionary[key1][key2] = value; | |
} | |
} | |
public Dictionary<K2, V> this[K1 key1] | |
{ | |
get | |
{ | |
return baseDictionary[key1]; | |
} | |
set | |
{ | |
baseDictionary[key1] = value; | |
} | |
} | |
public void Add(K1 key1, K2 key2, V value) | |
{ | |
if(!baseDictionary.ContainsKey(key1)) | |
{ | |
baseDictionary.Add(key1, new Dictionary<K2, V>()); | |
} | |
baseDictionary[key1].Add(key2, value); | |
} | |
public bool ContainsKey(K1 key1) | |
{ | |
if (!baseDictionary.ContainsKey(key1)) | |
{ | |
return false; | |
} | |
return true; | |
} | |
public bool ContainsKey(K1 key1, K2 key2) | |
{ | |
if (!baseDictionary.ContainsKey(key1)) | |
{ | |
return false; | |
} | |
if(!baseDictionary[key1].ContainsKey(key2)) | |
{ | |
return false; | |
} | |
return true; | |
} | |
public bool Remove(K1 key1, K2 key2) | |
{ | |
if(!baseDictionary.ContainsKey(key1)) | |
{ | |
return false; | |
} | |
if(!baseDictionary[key1].Remove(key2)) | |
{ | |
return false; | |
} | |
if(baseDictionary[key1].Count == 0) | |
{ | |
return baseDictionary.Remove(key1); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment