[英]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.