|
...
The yield return op code is one of my favorites in its neatness ( and,
I think, is unique to C# ). Here is an extension method which returns
an IEnumerable interface to a sequence of Int which is parsed from a
string of comma separated numbers:
public static IEnumerable<int?> ParseLine(this string InLine)
{
string[] splitItems = InLine.Split(',');
foreach (string item in splitItems)
{
int? itemIntValue = item.DefaultParse();
yield return itemIntValue;
}
}
// DefaultParse is a method that extends the string class.
// It returns the integer value parsed from a string.
// If the string cant be parsed, it returns a null.
// The ? after int? makes the int a nullable type.
public static int? DefaultParse(this string InText)
{
int answer;
bool rv = int.TryParse(InText, out answer);
if (rv == true)
return answer;
else
return default(int?);
}
to use the method:
string textLine = "123,213,33,3534" ;
foreach( int? item in textLine.ParseLine( ))
{
if ( item == null )
MessageBox.Show("item could not be parsed") ;
else
MessageBox.Show( item.Value ) ;
}
As an Amazon Associate we earn from qualifying purchases.
This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].
Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.