Reputation: 7301
I have a method that expect IEnumerable<string>
as you can see here :
public static string FromDecimalAscii(IEnumerable<string> input)
{
return new string(input.Select(s => (char)int.Parse(s)).ToArray());
}
But every time the last record of my IEnumerable is empty so i got an error in this line because of that :
return new string(input.Select(s => (char)int.Parse(s)).ToArray());
So i have to remove that item from my IEnumerable
.
The error:Input string was not in a correct format
Any ideas will be appreciated.
Best regards
Upvotes: 0
Views: 579
Reputation:
You need just to filter collection with Where
:
return new string(input.Where(s => !string.IsNullOrEmpty(s))
.Select(s => (char)int.Parse(s)).ToArray());
You can also use extension method to use TryParse
:
static class Extensions
{
public delegate bool TryParseDelegate<TSource>(string s, out TSource source);
public static IEnumerable<TResult> WhereParsed<TSource, TResult>(
this IEnumerable<TSource> source,
TryParseDelegate<TResult> tryParse)
{
// TODO: check arguments against null first
foreach (var item in source)
{
TResult result;
if (tryParse(item != null ? item.ToString() : null, out result))
{
yield return result;
}
}
}
}
Usage:
var collection = input.WhereParsed<string, int>(int.TryParse)
.Cast<char>()
.ToArray();
return new string(collection);
Upvotes: 6