Skip to content

Instantly share code, notes, and snippets.

@christopherbauer
Last active August 29, 2015 14:21
Show Gist options
  • Save christopherbauer/eccd3e71493950eb784b to your computer and use it in GitHub Desktop.
Save christopherbauer/eccd3e71493950eb784b to your computer and use it in GitHub Desktop.
public static class RouteValueDictionaryExtensions
{
public static RouteValueDictionary FlattenEnumerablesForLink(this RouteValueDictionary routeValueDictionary)
{
var result = new RouteValueDictionary();
foreach (var key in routeValueDictionary.Keys)
{
var value = routeValueDictionary[key];
var enumerableValue = value as IEnumerable;
if (enumerableValue == null)
{
if (value != null && value.GetType().IsClass)
{
throw new ApplicationException("Do not use class types as values in RouteValueDictionary. This does not generate useful links");
}
result[key] = value;
continue;
}
var elements = new List<object>(enumerableValue.Cast<object>());
for (var index = 0; index < elements.Count; index++)
{
var newKey = string.Format("{0}[{1}]", key, index);
result[newKey] = elements[index];
}
}
return result;
}
}
class RouteValueDictionaryTests
{
[TestFixture]
public class when_flattening_enumerables
{
[Test]
public void then_should_flatten_enumerables_to_indexed_keys_array()
{
// Arrange
var routeValueDictionary = new RouteValueDictionary();
routeValueDictionary["Test"] = new[] {1, 2, 3};
// Act
var flatRouteValueDictionary = routeValueDictionary.FlattenEnumerablesForLink();
// Assert
Assert.That(flatRouteValueDictionary,
Has.Exactly(1)
.Matches<KeyValuePair<string, object>>(pair => pair.Key == "Test[0]" && (int)pair.Value == 1)
.And.Exactly(1)
.Matches<KeyValuePair<string, object>>(pair => pair.Key == "Test[1]" && (int)pair.Value == 2)
.And.Exactly(1)
.Matches<KeyValuePair<string, object>>(pair => pair.Key == "Test[2]" && (int)pair.Value == 3));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment