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

标签 c# linq syntax iteration 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]);
                    }
                }
            }
        }

最佳答案

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

var remoteAccessLogs = from log in EventLogs.GetEventLogs()
                       where log.LogDisplayName == "AAA"
                       from entry in log.Entries
                       where entry.Source == "BBB"
                       select entry;

(假设 remoteAccessLogs 在此调用之前为空,并且您很乐意直接对其进行迭代 - 如果您想要 ToList(),可以调用 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 更容易阅读。方法。不过,两者都可以。

关于c# - 将嵌套的 for 循环转换为单个 LINQ 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3183626/

相关文章:

c# - 使用自然顺序从文件夹加载文件

c# - 如何在 C# 中从 URL 检索 JSON 数据

c# - C#中的花括号

c - 为什么 GCC 在尝试返回结构指针时给我一个语法错误?

c# - 我可以在 C# 中声明全局推断变量吗?

asp.net - 这些 <%$ %> asp.net 标记标签叫什么?

C# Asp.net Membership.GetAllUsers 通过电子邮件订购

c# - asp.net core DI 只注入(inject)单例,作用域和 transient 不工作

asp.net-mvc - Linq to SQL 更新无法使用存储库模式进行

c# - 没有foreach的Linq?