I'm hoping to find a better way (maybe with a nice linq expression) to convert a string list like "41,42x,43" to a list of valid long's. The below code works, but just feels ugly.
string addressBookEntryIds = "41,42x,43";
var ids = addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries);
var addressBookEntryIdList =new List<long>();
foreach (var rec in ids)
{
long val;
if (Int64.TryParse(rec, out val))
{
addressBookEntryIdList.Add(val);
}
}
string addressBookEntryIds = "41,42x,43";
Func<string, long?> safeParse = (s) => {
long val;
if (Int64.TryParse(s, out val))
{
return val;
}
return null;
};
var longs = (from s in addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries)
let cand = safeParse(s)
where cand.HasValue
select cand.Value).ToList();
use regex
var list = Regex.Matches(@"41,42x,43", @"\d+").Cast<Match>().Select(x => Convert.ToInt64(x.Value)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With