How to use LINQ to query the Windows Event Log

Posted: (EET/GMT+2)

 

Being able to use .NET 3.5 and LINQ queries is a great ability for .NET developers. Since LINQ supports querying many different object types, you might wish to query for example the Windows Event Log with LINQ statements. Here's how to it.

Your first attempt might be to write code like this:

EventLog systemLog = new EventLog("System");
var events = from e in systemLog.Entries
             select e;

Unfortunately, this code fails to compile with the error message "Could not find an implementation of the query pattern for source type 'System.Diagnostics.EventLogEntryCollection'. 'Select' not found. Consider explicitly specifying the type of the range variable 'e'."

To fix this error, you could simply add the EventLogEntry type specifier to the statement like this:

EventLog systemLog = new EventLog("System");
var events = from EventLogEntry e in systemLog.Entries
             select e;

Now, it works just fine. The next step might be to add a where clause, for example like this:

EventLog systemLog = new EventLog("System");
var events = from EventLogEntry e in systemLog.Entries
             where e.Source == "eventlog" &&
                   e.InstanceId == 6007
             select e;

That's how to do it! Here's a nice MSDN article about how LINQ works, which gives you a great place to start.

Keywords: HowTo, LINQ, query Windows Event Log, EventLog.