Last active
August 29, 2015 14:21
-
-
Save christopherbauer/eccd3e71493950eb784b to your computer and use it in GitHub Desktop.
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
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; | |
} | |
} |
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
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