将嵌套的for循环转换为单个LINQ语句

Gra*_*ant 11 c# linq iteration syntax structure

有人可以帮我把这个嵌套结构变成一个LINQ语句吗?

        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]);
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 14

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;
Run Code Online (Sandbox Code Playgroud)

(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");
Run Code Online (Sandbox Code Playgroud)

Or for a list:

var remoteAccessLogs = EventLogs.GetEventLogs()
                                .Where(log => log.LogDisplayName == "AAA")
                                .SelectMany(log => log.Entries)
                                .Where(entry => entry.Source == "BBB")
                                .ToList();
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了重载的== for string,因为我发现它比调用Equals方法更容易阅读.要么会工作.