can someone please help me turn this nested structure into a single LINQ statement?
EventLog[] logs = EventLog.GetEventLogs();
for (int i = 0; i
Nested loops usually end up with multiple "from" clauses (which are converted into calls to SelectMany
by the compiler):
var remoteAccessLogs = from log in EventLogs.GetEventLogs()
where log.LogDisplayName == "AAA"
from entry in log.Entries
where entry.Source == "BBB"
select entry;
(That's assuming that remoteAccessLogs
is empty before this call, and that you're happy iterating over it directly - you can call ToList()
if you want a List
.)
Here's the dot notation form:
var remoteAccessLogs = EventLogs.GetEventLogs()
.Where(log => log.LogDisplayName == "AAA")
.SelectMany(log => log.Entries)
.Where(entry => entry.Source == "BBB");
Or for a list:
var remoteAccessLogs = EventLogs.GetEventLogs()
.Where(log => log.LogDisplayName == "AAA")
.SelectMany(log => log.Entries)
.Where(entry => entry.Source == "BBB")
.ToList();
Note that I've used the overloaded == for string as I find it easier to read than calling the Equals
method. Either will work though.