Convert nested for-loops into single LINQ statement

后端 未结 5 1123
一生所求
一生所求 2021-02-08 03:23

can someone please help me turn this nested structure into a single LINQ statement?

        EventLog[] logs = EventLog.GetEventLogs();
        for (int i = 0; i          


        
5条回答
  •  执念已碎
    2021-02-08 04: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;
    

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

提交回复
热议问题