I would like to use the Enumerable.Aggregate(...) method to concatenate a list of strings separated by a semicolon. Rather easy, isn't it?
Considering the following:
private const string LISTSEPARATOR = "; ";
- album.OrderedTracks is
List<TrackDetails>
- TrackDetails has DiscNumber Int16? property
The following statement will trow an exception if the sequence returned by Distinct() is empty (as the Aggregate() method doesn't apply on empty sequence):
txtDiscNumber.Text = album.OrderedTracks
.Where(a => a.DiscNumber.HasValue)
.Select(a => a.DiscNumber.Value.ToString())
.Distinct()
.Aggregate((i, j) => i + LISTSEPARATOR + j);
The workaround I am using:
List<string> DiscNumbers =
album.OrderedTracks
.Where(a => a.DiscNumber.HasValue)
.Select(a => a.DiscNumber.Value.ToString())
.Distinct()
.ToList();
if (!DiscNumbers.Any())
txtDiscNumber.Text = null;
else
txtDiscNumber.Text =
DiscNumbers.Aggregate((i, j) => i + LISTSEPARATOR + j);
Is there any better solution? Is it possible to do this in a single LINQ statement?
Thanks in advance.
StringBuilder
, although in your specific case you can useString.Join
, which will internally avoid excessive string concatenation, so not only does it handle this edge case better, but it will perform much better for non-trivial data sets. – Trochaic