Filtering Windows logs using lambda expressions on non-IEnumerable types

c#, event-log, linq

Solution

`EventLogEntryCollection` (the type of object returned by `x.Entries` in your query) only implements `IEnumerable`, not the generic `IEnumerable<EventLogEntry>`. To use it with Linq methods you will have to cast each element:

x => x.Entries.Cast<EventLogEntry>().Where(...

`Cast<T>()` accepts any `IEnumerable` and returns an `IEnumerable<T>`, where each element is simply casted to the requested type, raising a ClassCastException if this fails. Since `EventLogEntry` is the only type of object that should be in this collection, this is a safe operation.

(`OfType<T>()` is similar, except it will omit elements that cannot be cast to the requested type rather than raising an exception. In this particular case, the observable behavior should be identical.)

Problem

I'm trying to get and filter Windows logs based on some criteria, one of which is filter by `Message`. The `Message` property is in `EventLog.GetEventLogs().Entries.Message`. The problem is `Entries` is an `EventLogEntryCollection` and I can't run a lambda expression (where) on it. I also tried casting it to an IEnumberable (List) type but it throws an exception and says cannot cast. The other issue is that it's a read-only property which makes it practically impossible to create a new `EventLog` object and add entries to it manually. Initially what I tried was: ``` List<EventLog> filteredList = EventLog.GetEventLogs().Where( x => string.Equals(x.LogDisplayName, "Some Value")).Where(x => x.Entries.Where(... ``` But obviously `Entries.Where()` won't work because it's not an IEnumberable. I've been thinking about an alternate solution for hours but I'm hopeless now. Any help is greatly appreciated.

Original source