I've followed Martin Liversaege's answer from this question on Stack Overflow: What is the implementing class for IGrouping?
I've implemented my own class that derives from IGroupable as such:
public class AjaxResponseGroup<TKey, TElement> : IGrouping<TKey, TElement>
{
readonly List<TElement> elements;
public AjaxResponseGroup(IGrouping<TKey, TElement> ajaxResponseGroup)
{
if (ajaxResponseGroup == null)
{
throw new ArgumentNullException("ajaxResponseGrouping");
}
Key = ajaxResponseGroup.Key;
elements = ajaxResponseGroup.ToList();
}
public TKey Key { get; private set; }
public IEnumerator<TElement> GetEnumerator()
{
return this.elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
I've got this fun little LINQ statement in my controller:
var groupedAuthActions = unitOfWork.AuthActions.GetAll()
.WhereIf(q != null, x => x.Name.ToLower().Contains(q.ToLower()))
.OrderByDescending(authAction => authAction.CreatedOn)
.Select(authAction => new AuthActionsListViewModel
{
Id = authAction.Id.ToString(),
Name = authAction.Name,
Description = authAction.Description,
Grouping = authAction.Grouping
})
.GroupBy(authActions => authActions.Grouping)
.Select(g => new AjaxResponseGroup<string, AuthActionsListViewModel>(g))
.ToList();
Which is serialized with the following line:
string serializedObject = JsonConvert.SerializeObject(groupedAuthActions);
However, when that is converted to JSON, the key is not included in the string, instead, the groups are anonymous arrays:
[
[{
"Id": "5fb20278-2f5e-4341-a02d-070d360066cd",
"Name": "CreateAuthAction",
"Description": "Allows the user to create an AuthAction",
"Grouping": "User Management"
}, {
"Id": "1edc56d4-9529-4a18-8684-137d0ccfd4d3",
"Name": "ReadAuthAction",
"Description": "Allows the user to view the AuthActions within the system",
"Grouping": "User Management"
}],
[{
"Id": "f1332b37-44c2-4c86-9cbe-ea3983bf6dfe",
"Name": "DeleteAuthAction",
"Description": "Allows the user to delete an AuthAction",
"Grouping": "Test Group"
}]
]
Other than looking at the Grouping
property of the first item in the array, how am I to determine what the key of the group is when using the object in the front-end JavaScript?
Is the only/best solution to do something like: (I'd be doing iterative functions, but to illustrate the idea)
// myObj = JS Object from return JSON above
var firstGroup = myObj[0][0].Grouping;
I feel like there has to be a more elegant and "correct" way of doing things?