How to group a table by date in the C# and entityframework?

Asked

Viewed 51 times

0

Next, I have this table :

CREATE TABLE [dbo].[lcr_LogLastAccess] (
    [Id]                  INT           IDENTITY (1, 1) NOT NULL,
    [logl_Company]        VARCHAR (100) NULL,
    [logl_Name]           VARCHAR (100) NULL,
    [logl_Login]          VARCHAR (100) NULL,
    [logl_AccessdDate]    DATETIME      NULL,
    [logl_Host]           VARCHAR (150) NULL,
    [logl_Browser]        VARCHAR (100) NULL,
    [logl_VersionBrowser] VARCHAR (50)  NULL,
    [logl_Platform]       VARCHAR (50)  NULL,
    [logl_CreatedOn]      DATETIME      NULL,
    CONSTRAINT [PK_LogLastAccess] PRIMARY KEY CLUSTERED ([Id] ASC)
);

With this population : inserir a descrição da imagem aqui

I need to show on the screen the following :

Carrefour    18:19
Express      17:19
Mendes       14:19

That is, I need to group the companies(logl_Company) per access time (logl_AccessdDate)

What I did :

 using (var db = new AcessoContext()) 
            {
                //var maxSample = db.lcr_LogLastAccess
                //    .Where(coluna => coluna.logl_AccessdDate == db.lcr_LogLastAccess.Max(coluna => coluna.logl_AccessdDate))     //Pega a maior data e retornar em string
                //    .First();
                //grupos.SelectMany(a => a.Where(b => b.logl_AccessdDate == a.Max(c => c.logl_AccessdDate)));

                var lista = new List<AcessoModel>();

                var grupos = db.lcr_LogLastAccess.AsEnumerable().GroupBy(coluna => coluna.logl_Company);


               foreach (var empresa in grupos)
                {
                    Console.WriteLine(empresa);
                }
                Console.WriteLine(lista.Count() + "\n");
                Console.ReadLine();


                //PARA CADA EMPRESA NA COMPANY IMPRIMIR A LINHA INTEIRA QUE A DATA SEJA MAIS RECENTE      
            }

But the count itself shows that the list is empty. and the groupby foreach returns System.Linq.Grouping`2[System.String,CONSOLE_TESTE2.Accessomodel] Grateful..

EDIT :------------------- The following code worked :

using (var db = new AcessoContext()) 
            {
                var grupos = db.lcr_LogLastAccess.GroupBy(g => g.logl_Company).Select(s => new
                {
                    Empresa = s.Key,
                    DataDeAcesso = s.Max(m => m.logl_AccessdDate)
                }).ToList();

                foreach( var empresa in grupos)
                {
                    Console.WriteLine(empresa);
                }
                
            }
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.