Raba - Defend your code RSS 2.0
# Monday, February 11, 2008

I've tried to write a simple code today GetEverythingButTheFirstElement() -> a code that get the all elements but the first one.

of course I've started with the old fashioned way:

   1:  string[] firstOne = new string[args.Count() - 1];
   2:  for (int i = 1; i < args.Count(); i++)
   3:  {
   4:   
   5:      firstOne[i - 1] = args[i];
   6:   
   7:  }

Now I've start refactoring it to something more C#3.0-able and it looks like this one:

   1:  // The method to use as the predicate for the where
   2:  public static bool GetAllElementsButTheFirstOne(string s, int i)
   3:  {
   4:      if (i == 0)
   5:          return false;
   6:   
   7:      return true;
   8:  }
   9:   
  10:  //The usage at my code
  11:  IEnumerable<string> secondTemp = args.Where(GetAllElementsButTheFirstOne);

Here happen something strange, the secondTemp do not hold objects in it, looks strange? no! it uses a lazy load thanks to the Linq defaults, so I've added this line at the end:

   12:  string[] secondOne = secondTemp.ToArray<string>();

So I decided to refactor this code a little bit more, I didn't like the string that the Where() force me to write, so I've added my own Where:

   1:  public static class Extensions
   2:  {
   3:      public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<int, bool> predicate)
   4:    
   5:      {
   6:          for(int i=0; i < source.Count(); i++)
   7:          {
   8:              if (predicate(i))
   9:                 yield return source.ElementAt(i);
  10:          }
  11:      }
  12:  }

This looks awesome now I can write it just like this:

   1:  public static bool GetAllElementsButTheFirstOne(int i)
   2:  {
   3:      if (i == 0)
   4:          return false;
   5:      return true;
   6:  }

But Hey, what do you think about this code?

   1:  IEnumerable<string> thirdTemp = args.Where((int i) => { return i > 0; });

Haaa, now it looks good.

This is not the first time I am writing lambda expression but I still thinking to my self how much I should read&code so this will be my natural way of thinking... for now it take me more time to write it than in the casual way.

Cheers.

Monday, February 11, 2008 11:32:49 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C#3.0 | LINQ

Comments are closed.
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Shani Raba
Sign In
Statistics
Total Posts: 145
This Year: 0
This Month: 0
This Week: 0
Comments: 97
Cool Stuff
Add to Technorati Favorites
Themes
Pick a theme:
All Content © 2012, Shani Raba
DasBlog theme 'Business' created by Christoph De Baene (delarou)