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)
4: if (i == 0)
5: return false;
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)
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)
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.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.