Filtering Windows logs using lambda expressions on non-IEnumerable types

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.

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


Need Your Help

Error: Deleted row information cannot be accessed through the row

c# datagrid dataset runtime

To whom this may concern, I have searched a considerable amount of time, to work a way out of this error

Integrated Windows Auth Migration to ADFS 1.0 asp.net

c# asp.net iis-7 adfs

I am planning to do some migration from Integrated windows auth to ADFS 1.0 for one of my web application in Asp.net/c#, Problem i am having is i cannot completely migrate to this new infrastructur...

What does a BufferedReader constructor expect a FileReader

java file file-io io

I need to understand the difference between these two classes and how they work with each other. I understand that FileReader reads characters from a file one character at a time and the BufferedRe...