Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a clean way to convert a string list to valid List<long> in C#

Tags:

c#

c#-4.0

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);
    }
}
like image 575
Peter Kellner Avatar asked Nov 23 '12 16:11

Peter Kellner


2 Answers

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();
like image 111
SAJ14SAJ Avatar answered Nov 14 '22 23:11

SAJ14SAJ


use regex

var list = Regex.Matches(@"41,42x,43", @"\d+").Cast<Match>().Select(x => Convert.ToInt64(x.Value)).ToList();
like image 42
burning_LEGION Avatar answered Nov 14 '22 22:11

burning_LEGION