Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Challenge: C# Foreach - Before, After, Even, Odd, Last, First

Tags:

c#

foreach

Since C# doesn't have a before,after,last,first etc. as part of its foreach. The challenge is to mimic this behavior as elegantly as possible with the following criteria:

  1. Must allow: before, first, even, odd, last, after events
  2. Give an option execute/not execute the primary function (function executed on all objects of the collection) during the events listed in #1

If you can exceed the above criteria, pleases do!

I'll post my answer below, but its not elegant nor is it feasible, so I would like to see what the community can conjure up.

hard coded for loops get annoying sometimes =(

like image 532
Omar Avatar asked Oct 19 '09 05:10

Omar


People also ask

Is HackerRank a beginner?

HackerRank is very good for beginners so even if you want to print your first program “Hello World!” then definitely HackerRank gives this opportunity to you. It has a pretty good UI with boilerplate code pre-written that helps beginners to start competitive coding.

Is HackerRank for free?

All Free. No Credit Card Required.

Where can I solve C programming questions?

Where can I get C Programming Questions and Answers with Explanation? IndiaBIX provides you lots of fully solved C Programming questions and answers with explanation. Fully solved examples with detailed answer description, explanation are given and it would be easy to understand.


2 Answers

LINQ...

  • after: .SkipWhile(predicate) (left vague as your meaning isn't clear)
  • before: .TakeWhile(predicate) (left vague as your meaning isn't clear)
  • last: .Last()
  • first: .First()
  • odd: .Where((x,i)=>i%2==1)
  • even: .Where((x,i)=>i%2==0)
like image 173
Marc Gravell Avatar answered Oct 19 '22 11:10

Marc Gravell


Jon Skeet wrote SmartEnumerable for this purpose. It's easily extended to provide IsOdd and IsEven properties.

Marc Gravell's answer is good because it's simple, but it will be less performant for cases when you first want to do something on all the odd elements and then on all the even elements, since that would have you iterate over all elements twice, while only a single time is strictly necessary.

I suppose you could write a function from an element to some enumeration and group all elements by the enumeration value they map to. Then you can easily handle each group seperately. But I'm not sure how this would perform, as I'm not sure what LINQ grouping specifically does and how much it's deferred.

like image 34
Joren Avatar answered Oct 19 '22 13:10

Joren