Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7704803
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T23:45:48+00:00 2026-05-31T23:45:48+00:00

Which is the best way to loop thru an list? is for loop better

  • 0

Which is the best way to loop thru an list? is for loop better than numerous List class’s find method? Also if i use its find methed as i mentioned below which is anonymous delegate an instance of an predicate delegate, does it better than using lambda expression? Which one will execute faster?

var result = Books.FindLast(
        delegate(Book bk)
        {
            DateTime year2001 = new DateTime(2001,01,01);
            return bk.Publish_date < year2001;
        });
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T23:45:49+00:00Added an answer on May 31, 2026 at 11:45 pm

    It’s a complex question because it involves a lot of different topics.

    In general, delegates are many times slower than a simple function call but to enumerate a list (via foreach) is terribly slow too.

    If you really care about performance (but do not do it a-priori, profile!) you should avoid delegates and enumerations. First big step (whenever possible) could be to use a Hashtable instead of a simple list.

    Examples

    Now some examples, I’ll write the same function in different ways, from the more readable (but slower) to the less readable (but faster). I omit every error checking but a real world function shouldn’t (at least some asserts are required).

    This function uses LINQ, it’s the more easy to understand but the slowest.
    Note the books can be a generic enumeration (it’s not required to be a List<T>)

    public static Book FindLastBookPublishedBefore(IEnumerable<Book> books, 
                                                   DateTime date)
    {
     return books.FindLast(x => x.Publish_date < date);
    }
    

    Same as before but without LINQ. Note that this function
    handles a special case: the list doesn’t contains any eligible book.

    public static Book FindLastBookPublishedBefore(IEnumerable<Book> books,
                                                   DateTime date)
    {
     Book candidate = null;
     foreach (Book book in books)
     {
      if (candidate == null || candidate.Publish_date > book.Publish_date)
       candidate = book;
     }
    
     return candidate;
    }
    

    Same as before but without enumeration, note that this function
    handles a special case: the list doesn’t contains any eligible book.

    public static Book FindLastBookPublishedBefore(List<Book> books,
                                                   DateTime date)
    {
     Book candidate = null;
     for (int i=0; i < books.Count; ++i)
     {
      if (candidate == null || candidate.Publish_date > books[i].Publish_date)
       candidate = books[i];
     }
    
     return candidate;
    }
    

    Same as before but with a SortedList<T> as suggested by @MaratKhasanov. Please note that with this container you’ll have the good performances during the search but insertion of a new element can be more slow than a normal unsorted list (because list itself must be kept sorted). If the number of elements in the list is very high you may think to write your own sorted list using a Hashtable (using, for example, the year as key for the first level).

    public static Book FindLastBookPublishedBefore(SortedList<Book> books,
                                                   DateTime date)
    {
     Book candidate = null;
     for (int i=0; i < books.Count; ++i)
     {
      DateTime publishDate = books[i].Publish_date;
    
      if (publishDate > date)
       return candidate;
    
      if (candidate == null || candidate.Publish_date > publishDate)
       candidate = books[i];
    
     }
    
     return candidate;
    }
    

    Now an example a little bit more complex but with best search performance. Algorithm is derived from an ordinary binary search (note that if you want to match the first element that matches the predicate you may use the List.BinarySearch method directly).
    Note that code is untested and can be optimized too, please consider it just an example.

    public static Book FindLastBookPublishedBefore(List<Book> books,
                                                   DateTime date)
    {
     int min = 0, max = books.Count;
     Book candidate = null;
    
     while (min < max)
     {
      int mid = (min + max) / 2;
      Book book = books[mid];
    
      if (book.Publish_date > date)
       max = mid - 1;
      else
      {
       candidate = book;
       ++min;
      }
    
      if (min >= max)
       break;
     }
    
      return candidate;
    }
    

    Before moving to a more complex container you may think to keep your SortedList<T> unsorted until the first search. It’ll be really slow (because it will sort the list too) but inserts will be as fast as a normal list (but you have to try with real world data). Anyway last algorithm can be optimized a lot.

    Maybe if you have so many items in your collection that you can’t manage them with a normal collection you may think to move everything to a database…lol

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Which is Best way to send data to aspx page, and why ? using
Which is the best way of implementing a language translation for mutli -lang site.
Which is the best way (in performance and security) to send multiple parameters to
Which is the best way to sanitize content? An example... Example - Before sanitize:
Which is the best way to read and parse an Fixed Width Text File
Which is the best way to manage a website with one or more mirrors
Which is the best way to registered event for example if I wanto to
Which is the best way to perform the following: Lets say i have a
Please tell me which is the best way to unset middle element of associative
I have a for loop to loop through my list of SliderItems which contain

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.