繁体   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