Thursday, September 8, 2016

Parsing CSV string with LINQ

// As list of strings
List<string> ids = idsCsv
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.Where(x => !String.IsNullOrWhiteSpace(x))
.ToList();


// As list of integers
var ids = csvIds
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
int id;
return int.TryParse(x, out id) ? id : -1;
})
.Where(x => x != -1)
.ToList();