![](/img/trans.png)
[英]How to set value to a certain property of each object in a collection of objects using LINQ
[英]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();
但我不知道该如何满足自己的需求。 有人可以帮我吗?
使具有相同ProductType
的Components
组。 从组的结果集合中,选择组中的第一个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.