简体   繁体   中英

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

I have an entity:

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

ProductType

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

I'm trying to get list of Product that contains 15 random items (5 per ProductType) in single LINQ.

ComputerCase, GraphicCard and Harddrive inherts from same base class

For now I have something like that:

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

but I have no idea how could I achive what I need. Can anyone help me with that?

Make groups of Components with the same ProductType . From the resulting collection of groups take the first Component in the group. From that result take the first 5, items.

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

Of course, if you really want a proper random, you'll have to fetch all Component groups to local memory and use RND to extract random groups and random element from each selected group

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM