c# - Remove an item from ienumerable<string> -
i have method expect ienumerable<string>
can see here :
public static string fromdecimalascii(ienumerable<string> input) { return new string(input.select(s => (char)int.parse(s)).toarray()); }
but every time last record of ienumerable empty got error in line because of :
return new string(input.select(s => (char)int.parse(s)).toarray());
so have remove item ienumerable
.
the error:input string not in correct format
ideas appreciated.
best regards
you need filter collection where
:
return new string(input.where(s => !string.isnullorempty(s)) .select(s => (char)int.parse(s)).toarray());
you can use extension method use tryparse
:
static class extensions { public delegate bool tryparsedelegate<tsource>(string s, out tsource source); public static ienumerable<tresult> whereparsed<tsource, tresult>( 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);
Comments
Post a Comment