我已经关注了堆栈溢出问题的Martin Liversaege回答:What is the implementing class for IGrouping?
我已经实现了我自己的类,它来自IGroupable:
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();
}
}
我的控制器中有这个有趣的小LINQ语句:
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();
使用以下行序列化:
string serializedObject = JsonConvert.SerializeObject(groupedAuthActions);
但是,当它转换为JSON时,键不包含在字符串中,而是组是匿名数组:
[
[{
"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"
}]
]
除了查看数组中第一项的Grouping
属性外,在前端JavaScript中使用该对象时,如何确定组的键是什么?
是唯一/最佳解决方案,例如:(我会做迭代功能,但要说明这个想法)
// myObj = JS Object from return JSON above
var firstGroup = myObj[0][0].Grouping;
我觉得必须有一个更优雅,更正确的&#34;做事的方式?