Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Windows logs using lambda expressions on non-IEnumerable types

Tags:

c#

linq

event-log

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.

like image 406
PoweredByOrange Avatar asked May 02 '13 17:05

PoweredByOrange


1 Answers

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.)

like image 138
cdhowie Avatar answered Sep 22 '22 02:09

cdhowie