簡體   English   中英

LINQ-從數據庫中為每個對象屬性值獲取x個對象

[英]LINQ - take x objects from database for each object property value

我有一個實體:

public class Component
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ProductType Type { get; set; }
}

產品類別

public enum ProductType
{
    Harddrive = 1,
    GraphicCard,
    ComputerCase,
}

我正在嘗試獲取在單個LINQ中包含15個隨機項(每個ProductType 5個)的產品列表。

來自相同基類的ComputerCase,GraphicCard和Harddrive繼承

現在我有這樣的事情:

        var response = db.Components
            .Select(x => new Product
            {
                Id = x.Id,
                Name = x.Name,
                Type = x.Type,
            }).ToList();

但我不知道該如何滿足自己的需求。 有人可以幫我嗎?

使具有相同ProductTypeComponents組。 從組的結果集合中,選擇組中的第一個Component 從結果中得出前5個項目。

var result = myComponents.                    // take the collection of Components
    .GroupBy(component => component.Type)     // group this into groups of components with same Type
    .Select(group => group.FirstOrDefault())  // from every group take the first element
    .Take(5)                                  // take only the first five

當然,如果您確實想要適當的隨機數,則必須將所有Component組提取到本地內存,並使用RND從每個選定的組中提取隨機組和隨機元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM