[英]Using Linq to Get a List of Objects to a Distinct Grouped List
所以我现在有一个在工作 API 中返回的 object 的列表。
public class ShoppingListItemDto
{
public int ShoppingListItemId { get; set; }
public string Name { get; set; }
public string Category { get; set; }
}
我想把它放到一个分组列表 object 中。 像这样的东西:
public class GroupedShoppingListItemDto
{
public string Category { get; set; }
public List<ShoppingListItemDto> ShoppingListItemDto { get; set; }
}
我找到了这篇文章并将以下内容放在一起,但我似乎无法让它拉入嵌套对象。
var list = _context.ShoppingListItems
.GroupBy(sli => new { sli.Category })
.Select(sli => new GroupedShoppingListItemDto { }).ToList();
例如,我希望 linq 查询返回如下内容:
{
"category":"produce",
"items": [
{
"id":1,
"name":"lettuce",
"category":"produce"
},
{
"id":4,
"name":"cucumber",
"category":"produce"
}
],
"category":"meat",
"items": [
{
"id":2,
"name":"chicken",
"category":"meat"
},
{
"id":3,
"name":"steak",
"category":"meat"
}
]
}
您需要对Select
查询进行ToList
。
var newList = list.GroupBy(x => x.Category)
.Select(x => new GroupedShoppingListItemDto { Category = x.Key, ShoppingListItemDto = x.ToList() });
它应该有效
所以你有一个 ShoppingListItems 序列,每个 ShoppingListItem 都有一个 Category,它是一个字符串。 一些ShoppingListItems
具有相同的类别。
您想要创建具有相同类别的 ShoppingListItem 组。 你是对的,为此你需要使用Enumerable.GroupBy的重载之一。
你想要一个特定的 output 格式。 在这种情况下,将 GroupBy 与参数 ResultSelector 一起使用:
var result = _context.ShoppingListItems.GroupBy(
// parameter KeySelector: make groups of ShopplingListitems with same Category
shoppingListItem => shoppingListItem.Category,
// parameter ResultSelector: for every category, and all ShoppingListItems
// with this category make one new GroupedShoppingListItemDto
(category, shoppingListItemsWithThisCategory) => new GroupedShoppingListItemDto
{
Category = category,
ShoppingListItems = shoppingListItemsWithThisCategory.ToList(),
})
// execute the query:
.ToList();
请注意,您的 GroupedShoppingListItemDto 中的每个 ShoppingListItem 都有一个您已经知道其值的类别:它等于 GroupedShoppingListItemDto.Category。 如果您有 1000 个类别为“肉”的 ShoppingListItems,您将传递相同的值超过 1000 次,这非常浪费处理能力。
因此,如果您只在此过程中本地使用结果,请考虑使用匿名类型:
var result = _context.ShoppingListItems.GroupBy(shoppingListItem => shoppingListItem.Category,
(category, shoppingListItemsWithThisCategory) => new
{
Category = category,
ShoppingListItems = shoppingListItemsWithThisCategory.Select(shoppingListItem => new
{
// Select only the properties that you plan to use:
Id = shoppingListItem.Id,
Name = shoppingListItem.Name,
...
// No need to select, you already know the value
// Category = shoppingListItem.Category
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.