Convert nested for-loops into single LINQ statement

浪尽此生 提交于 2019-12-03 05:59:17

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

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.

Try this:

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

However if performance is an issue I would expect this has at least the same algorithmic complexity, if not worse, as we are iterating over the list again to AddRange.

Try the following:

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

I have this solution, and I'm assuming that remoteAccessLogs is of type List

remoteAccessLogs.AddRange(

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

Edit

I forgot about the where clauses

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

Have a look:

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);
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!