-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Start getting multiple same key working
- Loading branch information
Showing
2 changed files
with
157 additions
and
16 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
using System.Collections; | ||
using System.Collections.Generic; | ||
|
||
namespace IntelOrca.Biohazard.BioRand.Routing | ||
{ | ||
internal class MultiSet<T> : ICollection<T>, IEnumerable<T> | ||
{ | ||
private readonly Dictionary<T, int> _dict = new Dictionary<T, int>(); | ||
private int _count; | ||
|
||
public int Count => _count; | ||
public bool IsReadOnly => false; | ||
|
||
public void Add(T item) | ||
{ | ||
_dict.TryGetValue(item, out var count); | ||
_dict[item] = count + 1; | ||
_count++; | ||
} | ||
|
||
public void AddRange(IEnumerable<T> items) | ||
{ | ||
foreach (var item in items) | ||
{ | ||
Add(item); | ||
} | ||
} | ||
|
||
public bool Remove(T item) | ||
{ | ||
if (_dict.TryGetValue(item, out var count)) | ||
{ | ||
if (count > 1) | ||
{ | ||
_dict[item] = count - 1; | ||
_count--; | ||
return true; | ||
} | ||
else | ||
{ | ||
_dict.Remove(item); | ||
if (count == 1) | ||
{ | ||
_count--; | ||
return true; | ||
} | ||
} | ||
} | ||
return false; | ||
} | ||
|
||
public int GetCount(T item) | ||
{ | ||
_dict.TryGetValue(item, out var count); | ||
return count; | ||
} | ||
|
||
public void Clear() | ||
{ | ||
_dict.Clear(); | ||
_count = 0; | ||
} | ||
|
||
public bool Contains(T item) => GetCount(item) > 0; | ||
|
||
public void CopyTo(T[] array, int arrayIndex) | ||
{ | ||
foreach (var item in this) | ||
{ | ||
array[arrayIndex++] = item; | ||
} | ||
} | ||
|
||
bool ICollection<T>.Remove(T item) => Remove(item); | ||
|
||
public IEnumerator<T> GetEnumerator() | ||
{ | ||
foreach (var kvp in _dict) | ||
{ | ||
for (var i = 0; i < kvp.Value; i++) | ||
{ | ||
yield return kvp.Key; | ||
} | ||
} | ||
} | ||
|
||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | ||
} | ||
} |
This file contains 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