static IEnumerable<T> FindUniqueNumbersInCollection<T>(ICollection<T> value)
{
Dictionary<T, byte> hash = new Dictionary<T, byte>();
foreach (T val in value)
{
if (hash.ContainsKey(val)) { hash[val] = 1; continue; }
hash.Add(val, 0);
}
List<T> unique = new List<T>();
foreach (KeyValuePair<T, byte> kvp in hash)
{
if (kvp.Value == 0) unique.Add(kvp.Key);
}
return unique;
}
I think this is finally correct. :)
var dict = new Dictionary<T, bool>();
foreach (var v in value)
dict[v] = dict.ContainsKey(v);
foreach (var pair in dict)
if (!pair.Value)
yield return pair.Key; //Algorithmically, as fast as possible
Or if you'd like some LINQ:
var dict = new Dictionary<T, bool>();
foreach (var v in value)
dict[v] = dict.ContainsKey(v);
return dict.Keys.Where(k => !dict[k]); //*COULD* be slower on lots of collisions
Or even
var dict = new Dictionary<T, bool>();
foreach (var v in value)
dict[v] = dict.ContainsKey(v);
return dict.Where(p => !p.Value).Select(p => p.Key); //"Fastest".. but not really
I wouldn't say it's "more efficient" than yours (it's really not -- they're pretty much the same), but it's definitely shorter.
If you want overkill efficiency (at the cost of accuracy), you can always use a Bloom Filter!
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