Grant Grant - 1 month ago 8
C# Question

Convert nested for-loops into single LINQ statement

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]);
}
}
}
}

Answer

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.