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

时间:2010-07-06 05:12:19

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

5 个答案:

答案 0 :(得分:14)

嵌套循环通常最终会有多个“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();

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

答案 1 :(得分:0)

试试这个:

 EventLog[] logs = EventLog.GetEventLogs(); 
 remoteAccessLogs.AddRange(
   logs.Where(l => l.LogDisplayName.Equals("AAA"))
     .Select(l => l.Entries)
     .Where(le => le.Source.Equals("BBB"));

然而,如果性能是一个问题,我预计这至少会有相同的算法复杂度,如果不是更糟,因为我们再次在列表上迭代到AddRange。

答案 2 :(得分:0)

尝试以下方法:

from log in logs 
where log.LogDisplayName.Equals("AAA")
select 
   (from entry in log.Entries
    where entry.Source.Equals("BBB")
    select entry);

答案 3 :(得分:0)

我有这个解决方案,我假设remoteAccessLogs的类型为List

remoteAccessLogs.AddRange(

        from log in EventLog.GetEventLogs()
        from entry in log.Entries.Cast<EventLogEntry>()
        select entry
    );

修改

我忘记了where子句

List<EventLogEntry> remoteAccessLogs = new List<EventLogEntry>();


    remoteAccessLogs.AddRange(

        from log in EventLog.GetEventLogs()
        where log.LogDisplayName.Equals("AAA")
        from entry in log.Entries.Cast<EventLogEntry>()
        where entry.Source.Equals("BBB")
        select entry
    );

答案 4 :(得分:0)

看看:

List<Entries> result = new List<Entries>();

GetEventLogs().Where(x => x.LogDisplayName.Equals("AAA")).ToList().ForEach(delegate(Log en)
{
    en.Entries.Where(y => y.Source.Equals("BBB", StringComparison.InvariantCultureIgnoreCase)).ToList().ForEach(delegate(Entries ent)
    {
        result.Add(ent);
    });
});