2016-10-03 42 views
1

試圖讓我的頭在Linq周圍,同時記錄早上登錄的時間,這應該是我進入辦公室的時間。使用Linq分組每日最早的入場號碼

到目前爲止我的代碼是:

EventLog SecurityLog = new EventLog("Security"); 

var AccountLoggedOnEntries = SecurityLog.Entries.Cast<EventLogEntry>() 
    .Where(x => x.InstanceId == 4624) 
    .Select(x => new 
    { 
     DateGenerated = x.TimeGenerated.ToShortDateString() 
     , 
     TimeGenerated = x.TimeGenerated.ToShortTimeString() 
     , 
     x.Message 
    }) 
    .ToList(); 

DgvLogSummary.DataSource = AccountLoggedOnEntries; 

DgvLogSummary.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; 

我要篩選的結果,這樣我只有每天一個條目,這是最早的時候。

在SQL中,我通常會選擇最早條目的消息,然後按所有字段進行分組。

如何在Linq中執行類似的查詢?

+0

最早進入?您是否在Linq中使用MIN()或MAX()? –

+0

類別。我不知道我在做什麼。我的頭非常多,處於SQL模式 –

回答

4

在LINQ你會GROUP BY,排序各組,並選擇第一項:

var AccountLoggedOnEntries = log.Entries.Cast<EventLogEntry>() 
    .Where(x => x.InstanceId == 4624) 
    .GroupBy(x => x.TimeGenerated.Date) 
    .Select(g => g.OrderBy(x => x.TimeGenerated).First()) 
    .Select(x => new { 
     DateGenerated = x.TimeGenerated.ToShortDateString() 
    , TimeGenerated = x.TimeGenerated.ToShortTimeString() 
    , x.Message 
    }) 
    .ToList(); 
-1

你可以GroupBy日期,然後選擇最短的時間

var AccountLoggedOnEntries = log.Entries.Cast<EventLogEntry>() 
    .Where(x => x.InstanceId == 4624) 
    .GroupBy(x => x.TimeGenerated.Date) 
    .Select(x => new { 
     DateGenerated = x.Key 
     , TimeGenerated = x.Min(y => y.TimeGenerated).ToShortTimeString() 
    }) 
    .ToList(); 

得到適當Message有點棘手。一個簡單的選擇是在以上Select投影中使用x.First().Message

-1

試試這個:

var AccountLoggedOnEntries = log.Entries.Cast<EventLogEntry>() 
       .Where(x => x.InstanceId == 4624) 
       .GroupBy(x => x.TimeGenerated.Date) 
       .Select(days => days.OrderBy(time => time.TimeGenerated).FirstOrDefault()) 
       .Select(x => new 
       { 
        DateGenerated = x.TimeGenerated.ToShortDateString() 
        , 
        TimeGenerated = x.TimeGenerated.ToShortTimeString() 
        , 
        x.Message 
       }) 
       .ToList();