将嵌套的for循环转换为单个LINQ语句 [英] Convert nested for-loops into single LINQ statement

查看:172
本文介绍了将嵌套的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 之前是空的这个电话,你很高兴直接迭代它 - 如果你想要一个 List< T> ToList() c $ c>。)

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

请注意,我使用了重载的== for string,因为我觉得它比调用更容易阅读等于方法。要么会工作。

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语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆