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

Convert nested for-loops into single LINQ statement(将嵌套的 for 循环转换为单个 LINQ 语句)
本文介绍了将嵌套的 for 循环转换为单个 LINQ 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

嵌套循环通常以多个from"子句结束(编译器将其转换为对 SelectMany 的调用):

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;

(假设 remoteAccessLogs 在此调用之前为空,并且您很乐意直接对其进行迭代 - 如果您想要 ToList()代码>列表<T>.)

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

这是点符号的形式:

var remoteAccessLogs = EventLogs.GetEventLogs()
                                .Where(log => log.LogDisplayName == "AAA")
                                .SelectMany(log => log.Entries)
                                .Where(entry => entry.Source == "BBB");

或者列表:

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

请注意,我使用重载的 == 表示字符串,因为我发现它比调用 Equals 方法更容易阅读.两者都可以.

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.

这篇关于将嵌套的 for 循环转换为单个 LINQ 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)