Are you familiar with the special IEnumerable<T> stuff that was
introduced with .NET 2.0?  With it, you can do the following:

public IEnumerable<int> GetInts() {
   int currentIndex = 1;
   while (currentIndex < 5) {
     yield return currentIndex;
     currentIndex++;
   }
}

It doesn't return an array or List or anything else, but rather
returns the objects one at a time, so if you debug through the
following, you'll see the focus move back and forth from the two
methods.
foreach (int i in GetInts()) {
  Console.WriteLine(i);
}

If you're not familiar with this, check it out first, and practice
using it, since it's kind of a cool technique that really doesn't seem
to be used all that often.

If you are unfamiliar with the basics of lambdas, or at least
anonymous methods, you'll also need to know about those before using
TakeWhile.

TakeWhile allows you to loop through an IEnumerable<T> (either a
regular collection like a List<T> or a special IEnumerable<T> like
GetInts() above), then stop once a condition is met.  For example:
IEnumerable<int> newInts = GetInts().TakeWhile(i => i < 4);
At this point, newInts doesn't have anything in it.  But when you
iterate it like:
foreach (int i in newInts) {
  Console.WriteLine(i);
}
One at a time, the values 1 through 3 are retrieved and printed.  Once
GetInts() returns a value that is not less than 4, the TakeWhile
filter takes effect, and the loop stops.

You can also use it on any other normal collection:
string[] myStrings = new string[] { "a", "b", "c", "d" };
foreach (string s in myStrings.TakeWhile(s => s != "c")) {
  Console.WriteLine(s);
}
Will loop through "a" and "b", but will stop at "c".

Seems to be exactly the same as the following, but there may be one or
two minor differences:
foreach (string s in myStrings) {
  if (s != "c") {
    break;
  }
  Console.writeLine(s);
}

I personally haven't used this method, so I can't really think of a
good real-world example.  But if you're ever in a situation where you
need to retrieve from a collection or a logical result set while/until
a certain condition is met, this is what you're looking for.

On May 23, 5:32 pm, LarryFarrell <[email protected]> wrote:
> It seems like this method would address my problem.  However, I can't
> understand how to use it.  The documentation is useless.  Could anyone
> give me a clue because I can't even buy one, currently.
>
> TIF,
>
> --Larry--

Reply via email to