Posted By

pckujawa on 01/13/09


Tagged

String enum csharp enumerate


Versions (?)

Who likes this?

7 people have marked this snippet as a favorite

enajenkins
umang_nine
ddevening
paelgr
khouser
jalalx
danfinrud55


Create IEnumerable<string> to manually enumerate over string values


 / Published in: C#
 

URL: http://www.ondotnet.com/pub/a/dotnet/excerpt/progcsharp4_ch09-04/index.html

Ever need to enumerate over a collection of strings? Simple, just foreach(string str in stringContainer) and you've got them, right? Well, what if you want to enumerate over them manually? Basically, you can't (as far as I've found). You can do stringContainer.GetEnumerator(), but that returns a System.Collections.IEnumerator, which holds objects, not strings (thus requiring an explicit cast to get the string value). That is, you cannot do IEnumerator en = stringContainer.GetEnumerator(); en.MoveNext(); string myString = en.Current; You have to do string myString = Convert.ToString(en.Current);

I don't know why C# doesn't have this built in, but it doesn't (and trying to cast to IEnumerator<string> throws an exception). So, there are a lot of homegrown solutions out there, but this one is the easiest for my application. I needed to read in values from a file and assign them to string variables. Since there are a lot of variables, and their order is sometimes changed between versions, it is a pain to assign each variable by its array index (the array being created by reading in each line and splitting it with a comma). It is much easier to change the ordering of variables by simply moving the line up or down in the source code. Thus the need for an enumerator and my dilemma.

The URL refers to similar code from an O'Reilly book.

The 'yield return' statement essentially returns one value from a collection each time a value is needed (such as in a foreach or enum.MoveNext), but keeps track of ordering for you. Pretty slick. Google it for more info.

  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace testConsole
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. string[] stringArr = new string[] { "1", "2", "Text with spaces" };
  11. string text1;
  12. string text2;
  13. string text3;
  14. IEnumerator<string> stringEnum = Program.makeStringEnum(stringArr);
  15. stringEnum.MoveNext();
  16. text1 = stringEnum.Current; stringEnum.MoveNext();
  17. text2 = stringEnum.Current; stringEnum.MoveNext();
  18. text3 = stringEnum.Current; stringEnum.MoveNext();
  19. }
  20.  
  21. static IEnumerator<string> makeStringEnum(string[] arr)
  22. {
  23. foreach (string str in arr)
  24. {
  25. yield return str;
  26. }
  27. }
  28. }
  29. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: blueice8549 on December 25, 2010

Thanks,

Its very useful.... Keep up good work.....

You need to login to post a comment.