Query Linq group by

0

I want to build a linq query by applying group by but I have an extended class in which I have to match the feature class with the extended class.

IEnumerable<ModeloExtend> result = Context.Modelos
                                                .Where(x => x.LineaId == damas || x.LineaId == caballeros)
                                                .GroupBy(x => x.LineaId)
                                                .Select(g => new ModeloExtend
                                                {
                                                    ModeloExtendId = g.Key,
                                                    Descripcion = g.ElementAt()
                                                }).ToList();

I can not make the new selection

I want to do this but with GROUP BY eliminating the ORDER BY

List<ModeloExtend> result = Context.Modelos
                .Where(x => x.LineaId == damas || x.LineaId == caballeros)
                .OrderBy(x => x.LineaId)
                .Select(x => new ModeloExtend
                {
                    ModeloExtendId = x.ModeloId,
                    Descripcion = x.Descripcion 
                }).ToList();
    
asked by Pedro Ávila 03.07.2016 в 19:24
source

1 answer

2

In the linq that you define you are only defining simple properties of the entity Modelos does not apply the GROUP BY, at most you would use the DISTINCT ()

[Linq] Distinct and GroupBy using IEquatable < >

in this way duplicates of models will not appear

List<ModeloExtend> result = Context.Modelos
                .Where(x => x.LineaId == damas || x.LineaId == caballeros)
                .Select(x => new ModeloExtend
                {
                    ModeloExtendId = x.ModeloId,
                    Descripcion = x.Descripcion 
                }).Distinct().ToList();

Remember to implement the interface IEquatable<> in class ModeloExtend to be able to determine when entities are duplicated

    
answered by 04.07.2016 / 14:43
source