Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘myList’

C# Code Snippet: List.ForEach method

Do you ever use the List(T).ForEach Method in C#, if never, you’d better read this.

The syntax is :
public void ForEach(Action<T> action)

   1: static void Main()

   2: {

   3:     List<long> myList = new List<long>();

   4:     foreach (string item in "269, 361, 347, 355, 352, 346, 351, 354".Split(','))

   5:     {

   6:         myList.Add(long.Parse(item.Trim()));

   7:     }

   8:     myList.ForEach(FA);

   9: }

  10:  

  11: static void FA(long num)

  12: {

  13:     Console.WriteLine(num);

  14: }

Is that cool? It gives lots of convenience in coding!

  • Digg
  • DZone
  • Yahoo Buzz
  • Delicious
  • Reddit
  • StumbleUpon
  • SmakNews
  • Jumptags
  • Ping
  • Share/Bookmark

List(T).BinarySearch in C#

I think most of us are quite familiar with binary search. Binary search is an algorithm for locating the position of an element in a sorted list by checking the middle, eliminating half of the list from consideration, and then performing the search on the remaining half.If the middle element is equal to the sought value, then the position has been found; otherwise, the upper half or lower half is chosen for search based on whether the element is greater than or less than the middle element. The method reduces the number of elements needed to be checked by a factor of two each time, and finds the target value, if it exists in logarithmic time. A binary search is a dichotomy divide and conquer search algorithm.

In C#, .Net provide a List<T>.BinarySearch Method (T) which can be used easily. here is a demo:

   1: // Init a long type list

   2: var myList = new List<long>();

   3: foreach (var item in "269, 361, 347, 355, 352, 346, 351, 354".Split(','))

   4: {

   5:     myList.Add(long.Parse(item.Trim()));

   6: }

   7:  

   8: // sort

   9: myList.Sort();

  10: var ret = myList.BinarySearch(347);

  11: Console.WriteLine(ret);

Note, I have a ‘myList.Sort();’ before call the BinarySearch, why? It is because BinarySearch will Search the entire sorted System.Collections.Generic.List<T> for an element using the default comparer and returns the zero-based index of the element.

Yes, it is sorted list that binary search will operate on! So remember make your list sorted before call binary search function

  • Digg
  • DZone
  • Yahoo Buzz
  • Delicious
  • Reddit
  • StumbleUpon
  • SmakNews
  • Jumptags
  • Ping
  • Share/Bookmark