Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new Dictionary extension methods #45

Merged
merged 1 commit into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 163 additions & 16 deletions SharpHelpers/SharpHelpers.UnitTest/Dictionary/DictionaryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,184 @@
using SharpCoding.SharpHelpers;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SharpHelpers.UnitTest.Dictionary
{

[TestClass]
public class DictionaryTest
{
[TestMethod]
public void TestAddFormat()
public void AddFormat_ShouldAddFormattedStringToDictionary()
{
var dic = new Dictionary<int, DateTime>() { { 1, DateTime.Now }, { 2, DateTime.Now } };

// Arrange
var dictionary = new Dictionary<int, string>();

// Act
dictionary.AddFormat(1, "Hello, {0}!", "World");

// Assert
Assert.AreEqual("Hello, World!", dictionary[1]);
}

[TestMethod]
public void TestRemoveAll()
[ExpectedException(typeof(ArgumentNullException))]
public void AddFormat_ShouldThrowArgumentNullException_WhenDictionaryIsNull()
{
var dic = new Dictionary<int, DateTime>() { { 1, DateTime.Now }, { 2, DateTime.Now } };
dic.RemoveAll(a=> a.Key < 2 );
Assert.IsTrue(dic.Count() == 1);
// Arrange
Dictionary<int, string> dictionary = null;

// Act
dictionary.AddFormat(1, "Hello, {0}!", "World");

// Assert - [ExpectedException] handles the assertion
}

[TestMethod]
public void TestGetOrCreate()
public void RemoveAll_ShouldRemoveItemsBasedOnCondition()
{
var dic = new Dictionary<int,DateTime>() { { 1, DateTime.Now }, { 2, DateTime.Now} };
Assert.IsNotNull(dic.GetOrCreate(1));
Assert.IsNotNull(dic.GetOrCreate(3));
// Arrange
var dictionary = new Dictionary<int, string>
{
{ 1, "Apple" },
{ 2, "Banana" },
{ 3, "Avocado" }
};


// Act
dictionary.RemoveAll(kvp => kvp.Value.StartsWith("A"));

// Assert
Assert.AreEqual(1, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(2));
}
}

}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void RemoveAll_ShouldThrowArgumentNullException_WhenDictionaryIsNull()
{
// Arrange
Dictionary<int, string> dictionary = null;

// Act
dictionary.RemoveAll(kvp => kvp.Value.StartsWith("A"));

// Assert - [ExpectedException] handles the assertion
}

[TestMethod]
public void GetOrCreate_ShouldCreateAndReturnNewValue_WhenKeyDoesNotExist()
{
// Arrange
var dictionary = new Dictionary<int, List<string>>();

// Act
var result = dictionary.GetOrCreate(1);

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(0, result.Count);
Assert.IsTrue(dictionary.ContainsKey(1));
}

[TestMethod]
public void AddOrUpdate_ShouldAddNewItem_WhenKeyDoesNotExist()
{
// Arrange
var dictionary = new Dictionary<int, string>();

// Act
dictionary.AddOrUpdate(1, "NewValue");

// Assert
Assert.AreEqual("NewValue", dictionary[1]);
}

[TestMethod]
public void AddOrUpdate_ShouldUpdateExistingItem_WhenKeyExists()
{
// Arrange
var dictionary = new Dictionary<int, string>
{
{ 1, "OldValue" }
};

// Act
dictionary.AddOrUpdate(1, "UpdatedValue");

// Assert
Assert.AreEqual("UpdatedValue", dictionary[1]);
}

[TestMethod]
public void RemoveIfExists_ShouldReturnTrueAndRemoveItem_WhenKeyExists()
{
// Arrange
var dictionary = new Dictionary<int, string>
{
{ 1, "Value" }
};

// Act
var result = dictionary.RemoveIfExists(1);

// Assert
Assert.IsTrue(result);
Assert.IsFalse(dictionary.ContainsKey(1));
}

[TestMethod]
public void RemoveIfExists_ShouldReturnFalse_WhenKeyDoesNotExist()
{
// Arrange
var dictionary = new Dictionary<int, string>();

// Act
var result = dictionary.RemoveIfExists(1);

// Assert
Assert.IsFalse(result);
}

[TestMethod]
public void Merge_ShouldMergeDictionariesAndUpdateValues()
{
// Arrange
var dictionary = new Dictionary<int, string>
{
{ 1, "Value1" },
{ 2, "Value2" }
};

var otherDictionary = new Dictionary<int, string>
{
{ 2, "UpdatedValue2" },
{ 3, "Value3" }
};

// Act
dictionary.Merge(otherDictionary);

// Assert
Assert.AreEqual(3, dictionary.Count);
Assert.AreEqual("UpdatedValue2", dictionary[2]);
Assert.AreEqual("Value3", dictionary[3]);
}

[TestMethod]
public void ToReadableString_ShouldReturnFormattedStringRepresentationOfDictionary()
{
// Arrange
var dictionary = new Dictionary<int, string>
{
{ 1, "Value1" },
{ 2, "Value2" }
};

// Act
var result = dictionary.ToReadableString();

// Assert
Assert.AreEqual("{1: Value1, 2: Value2}", result);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.5.2" />
<PackageReference Include="MSTest.TestFramework" Version="3.5.2" />
</ItemGroup>
Expand Down
57 changes: 57 additions & 0 deletions SharpHelpers/SharpHelpers/DictionaryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,63 @@ public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> di
dictionary[key] = ret;
}
return ret;
}

/// <summary>
/// Tries to add a key-value pair to the dictionary. If the key already exists, it updates the value.
/// </summary>
/// <param name="dictionary">The dictionary to operate on.</param>
/// <param name="key">The key to add or update.</param>
/// <param name="value">The value to associate with the key.</param>
public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key))
{
dictionary[key] = value;
}
else
{
dictionary.Add(key, value);
}
}

/// <summary>
/// Removes the entry with the specified key if it exists in the dictionary, and returns a boolean indicating success.
/// </summary>
/// <param name="dictionary">The dictionary to operate on.</param>
/// <param name="key">The key to remove.</param>
/// <returns>True if the key was found and removed, otherwise false.</returns>
public static bool RemoveIfExists<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
{
return dictionary.Remove(key);
}

/// <summary>
/// Merges the entries from another dictionary into the current dictionary. If a key already exists, its value is updated.
/// </summary>
/// <param name="dictionary">The dictionary to operate on.</param>
/// <param name="otherDictionary">The dictionary to merge from.</param>
public static void Merge<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Dictionary<TKey, TValue> otherDictionary)
{
foreach (var kvp in otherDictionary)
{
dictionary.AddOrUpdate(kvp.Key, kvp.Value);
}
}

/// <summary>
/// Converts the dictionary into a readable string format, useful for debugging.
/// </summary>
/// <param name="dictionary">The dictionary to convert to a string.</param>
/// <returns>A string representation of the dictionary.</returns>
public static string ToReadableString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
{
var entries = new List<string>();
foreach (var kvp in dictionary)
{
entries.Add($"{kvp.Key}: {kvp.Value}");
}
return "{" + string.Join(", ", entries) + "}";
}
}
}
Loading