can someone please help me turn this nested structure into a single LINQ statement?
EventLog[] logs = EventLog.GetEventLogs();
for (int i = 0; i < logs.Length; i++)
{
if (logs[i].LogDisplayName.Equals("AAA"))
{
for (int j = 0; j < logs[i].Entries.Count; j++)
{
if (logs[i].Entries[j].Source.Equals("BBB"))
{
remoteAccessLogs.Add(logs[i].Entries[j]);
}
}
}
}
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<T>
.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With