sharee.bike-App/SharedBusinessLogic/Repository/Response/ComparableBikeDictionary.cs

65 lines
1.7 KiB
C#
Raw Normal View History

2024-04-09 12:53:23 +02:00
using System.Linq;
using System.Runtime.Serialization;
namespace ShareeBike.Repository.Response
{
public class ComparableBikeDictionary<S> : ComparableDictionary<S> where S : BikeInfoBase
{
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
var toCorrectDictionary = this.Where( x =>
!string.IsNullOrEmpty(x.Value.bike)
&& x.Key != x.Value.bike).ToArray();
foreach (var element in toCorrectDictionary)
{
Remove(element.Key);
if (ContainsKey(element.Value.bike))
{
// Remove duplicates.
Remove(element.Value.bike);
continue;
}
Add(element.Value.bike, element.Value);
}
}
/// <summary>
/// Removes a bike from dictionary.
/// </summary>
/// <typeparam name="T">Type of dictionary values to remove.</typeparam>
/// <param name="bikeId">If of bike to remove.</param>
/// <returns>True if at least one bike was removed, false if no bike was removed.</returns>
public bool RemoveByBikeId<T>(
string bikeId)
{
if (string.IsNullOrEmpty(bikeId))
{
// Nothing to do.
return false;
}
var bikeToRemove = this.FirstOrDefault(x => bikeId == x.Value.bike);
if (string.IsNullOrEmpty(bikeToRemove.Key))
{
// Bike is not contained in dictionary.
return false;
}
return Remove(bikeToRemove.Key);
}
/// <summary>
/// Gets a bike by bike id from dictionary.
/// </summary>
/// <typeparam name="T">Type of dictionary values to remove.</typeparam>
/// <param name="bikeId">If of bike to get.</param>
/// <returns>True if at least one bike was removed, false if no bike was removed.</returns>
public S GetByBikeId(
string bikeId)
=> this.FirstOrDefault(x => bikeId == x.Value.bike).Value;
}
}