Improve nested foreach performance C#

i have this following classes, in a windows store app project.

    public class Meeting
{
    public string Id { get; set; }
    public string Organizer { get; set; }
    public string Organization { get; set; }
    public string Name { get; set; }
    public string MeetingType { get; set; }
    public string Description { get; set; }
    public Address Address { get; set; } //X = LAT; Y=LNG
    public DateTime StartDate { get; set; }
    public DateTime EndTime { get; set; }
    public string Status { get; set; }
    public List<MeetingPoint> MeetingPoints { get; set; }
    public List<MeetingInvitee> Invitees { get; set; }
}

and this one

public class MeetingPoint
{
    public string id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Position { get; set; }
    public List<Attchments> Attachments { get; set; }
    public List<MeetingPoint> SubPoints { get; set; }
    public int AttachmentNumber { get; set; }
    public string details { get; set; }
    public string executiveSummary { get; set; }
    public string presenter { get; set; }
    public string coPresenter { get; set; }
    public Double duration { get; set; }
    public string purpose { get; set; }
    public string supportedBy { get; set; }
    public int num { get; set; }

}

In one of the pages, i do a search that looks like this, where i try to get the Attachments in each SubPoint of each MeetingPoint

foreach (var item in meeting.MeetingPoints)
        {
            foreach (var sub in item.SubPoints)

            {

                foreach (var at in sub.Attachments)
                {

                    ...

                }
            }

My question is if there is a more effective way of doing this, since having 3 nested foreach takes about 4 or 5 seconds.


I'm not certain about performance increase, I think you may see some, but if you want to get away from nested loops consider using lambda/SelectMany to get to the lowest collection you need to iterate over to do work against. In other words, if you're only going to be operating against attachments then consider something like this:

 var greatGandChildrenFlattened = parent.Children.SelectMany(c => c.GrandChildren.SelectMany(gc => gc.GreatGrandChildren));
 foreach (var item in greatGandChildrenFlattened)
 {
     //do work on item
 }

You can try to replace some of the foreach blocks with Parallel.ForEach . Just look for this in the output window "EventSourceException: No Free Buffers available from the operating system (eg event rate too fast)" and if it happens, replace one of the Parallel.ForEach invocations with a normal foreach block. This happens if events are fired too quickly and it may have a negative impact on the performance instead of helping you.

链接地址: http://www.djcxy.com/p/87962.html

上一篇: 带/不带引号的HTML属性

下一篇: 提高嵌套的foreach性能C#