Linq C # with order

3

I have a LINQ query that lists the birthdays of the current month:

        Ramal[] RamalAniver = (from a in db.Ramais
                               where a.sAniversario.Contains(DiaAniversario + "/" + MesAniversario) && a.bAtivo == true
                               select a)
                               .Union(
                               from c in db.Ramais
                               where c.sAniversario.Contains("/" + MesAniversario) && c.bAtivo == true
                               orderby c.sAniversario
                               select c
                               ).ToArray();

But when I set it up, the intention was in the first consultation to bring the birthday boy for the day as the first record, and on the second anniversary of the current month. The query is returning the records but the birthday party of the day does not come first ...

When the list is assembled the order is not maintained ... how do I keep it in the order I put in the Union?

    
asked by anonymous 07.11.2017 / 21:10

2 answers

0

Linq does not guarantee order maintenance, so you can use a trick.

Ramal[] RamalAniver =
    (from a in db.Ramais
    where a.sAniversario.Contains(DiaAniversario + "/" + MesAniversario) && a.bAtivo == true
    select new { Ramal = a, Ordem = 0 })
    .Union(
    from c in db.Ramais
    where c.sAniversario.Contains("/" + MesAniversario) && c.bAtivo == true
    orderby c.sAniversario
    select new { Ramal = c, Ordem = 1 })
    .OrderBy(n => n.Ordem)
    .Select(n => n.Ramal)
    .ToArray();

It's alright that it's adding a little more complexity, but so you stay within the context of Linq with its benefits.

Basically you would be creating a new type with 2 properties, one is Ramal and the other is int with the order imposed by your model, and after using it to sort the result, playing this auxiliary off to return only the data you want.

I believe this will solve your problem.

    
07.11.2017 / 23:12
0

I researched and added the result I got the solution:

I simplified the query by bringing only the birthday person of the month:

Extension [] RamalAniver = (from c in db.Ramais                                    where c.sAniversario.Contains ("/" + MonthAnniversary) & c.bActive == true                                    orderby c.sAniversario                                    select c                                    ) .ToArray ();

and using this expression I got the birthday boy of the day in first position and then in order of the day of the month:

RamalAniver = RamalAniver.OrderByDescending (x => x.s Anniversary == DiaAniversary                 + "/" + AnniversaryManual) .ThenBy (x => x.sAniversary) .ToArray ();

If anyone can detail the understanding of this expression, thank you.

    
09.11.2017 / 20:07