PkmnLib.NET/PkmnLib.Static/Libraries/DataLibrary.cs

62 lines
1.6 KiB
C#
Raw Normal View History

2024-09-30 12:20:45 +00:00
using System.Collections;
2024-07-20 14:12:39 +00:00
using System.Diagnostics.CodeAnalysis;
using PkmnLib.Static.Utils;
namespace PkmnLib.Static.Libraries;
/// <summary>
/// A basic library for data types. Stores data both by name and by index.
/// </summary>
2025-03-02 16:19:57 +00:00
public abstract class DataLibrary<T> : IEnumerable<T> where T : INamedValue
2024-07-20 14:12:39 +00:00
{
2024-09-30 12:20:45 +00:00
/// <summary>
/// The underlying data storage.
/// </summary>
protected readonly Dictionary<StringKey, T> Data = new();
2025-03-02 16:19:57 +00:00
2024-07-20 14:12:39 +00:00
private readonly List<T> _values = [];
/// <summary>
/// Adds a value to the library.
/// </summary>
public void Add(T value)
{
2024-09-30 12:20:45 +00:00
Data.Add(value.Name, value);
2024-07-20 14:12:39 +00:00
_values.Add(value);
}
/// <summary>
/// Removes a value from the library.
/// </summary>
public void Remove(T value)
{
2024-09-30 12:20:45 +00:00
Data.Remove(value.Name);
2024-07-20 14:12:39 +00:00
_values.Remove(value);
}
/// <summary>
/// Try to get a value from the library. Returns false if the value is not found.
/// </summary>
2024-09-30 12:20:45 +00:00
public bool TryGet(StringKey key, [MaybeNullWhen(false)] out T value) => Data.TryGetValue(key, out value);
2024-07-20 14:12:39 +00:00
/// <summary>
/// Get a random value from the library.
/// </summary>
public T GetRandom(IRandom random) => _values[random.GetInt(_values.Count)];
/// <summary>
/// The number of values in the library.
/// </summary>
public int Count => _values.Count;
/// <summary>
/// Whether the library is empty.
/// </summary>
public bool IsEmpty => _values.Count == 0;
2024-09-30 12:20:45 +00:00
/// <inheritdoc />
public IEnumerator<T> GetEnumerator() => _values.GetEnumerator();
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
2024-07-20 14:12:39 +00:00
}