Looking for a clean way to convert a list of strings to a valid List <long> in C #
I hope to find a better way (possibly with a nice linq expression) to convert a list of strings, like "41.42x, 43", into a list of valid lengths. The code below 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); } } +6
5 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(); +4
Well, here is the LINQ version, but itβs not quite so ugly!
string addressBookEntryIds = "41,42x,43"; var ids = addressBookEntryIds.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); Int64 converted; // Working value used within the select IEnumerable<Int64> values = ids.Select(x => new { Success = Int64.TryParse(x, out converted), Value = converted }).Where(x => x.Success) .Select(x => x.Value); The difference between this solution and Anderson is that TryParse is called only once for each record.
+1
Here is another version of LINQ:
String addressBookEntryIds = "41,42x,43"; Int64 val = 0; addressBookEntryIds .Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries) .Where(id => Int64.TryParse(id, out val)) .Select(id => val) .ToList() If you prefer a query expression, you can use:
from id in addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries) where Int64.TryParse(id, out val) select val +1
Just the output of your code, quite redundant (uses TryParse again and then Parse), but I think it works:
addressBookEntryIds.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries) .Where(id => { long val; return Int64.TryParse(id, out val); }) .Select(id => Int64.Parse(id)); 0