The magic of LINQ

Programming LINQ C#

For some LINQ is "dealing with entities" in terms of "dealing with database stuff". In reality you can solve almost any problem with LINQ.  Lets take for example this string

"2:54,3:08,2:36,4:16,3:08,2:47,4:12,3:16,2:51,5:35,3:55,2:21,3:02"

that holds the duration of all songs of an album.  How long lasts the hole album? How do you solve this? Split string, foreach loop, adding each duration to a TimeSpan variable?

You can solve this problem with only one single LINQ statement:

// Music-Album, given the duration of all songs
// => how long is the duration of whole album in seconds ?
"2:54,3:08,2:36,4:16,3:08,2:47,4:12,3:16,2:51,5:35,3:55,2:21,3:02"
.Split(',')
.Select(track => "0:" + track) // add hours
.Select(track => TimeSpan.Parse(track)) // otherwise we would need ParseExact()
.Select(track => track.TotalSeconds)
.Sum() + " seconds";

Problem: This only gives us the total time of the album in seconds.  You can alter this LINQ statement in order to get the duration in HH:MM:SS by using TimeSpan type and Aggregate method like this:

// Music-Album, given the duration of all songs
// => how long is the duration of whole album in HH:MM:SS ?
"2:54,3:08,2:36,4:16,3:08,2:47,4:12,3:16,2:51,5:35,3:55,2:21,3:02"
.Split(',')
.Select(track => "0:" + track) // add hours
.Select(track => TimeSpan.Parse(track)) // otherwise we would need ParseExact()
.Aggregate(TimeSpan.Zero, (t1, t2) => t1 + t2);

We can even purify this LINQ query further:

// Music-Album, given the duration of all songs [short version]
// => how long is the duration of whole album in HH:MM:SS ?
"2:54,3:08,2:36,4:16,3:08,2:47,4:12,3:16,2:51,5:35,3:55,2:21,3:02"
.Split(',')
.Select(track => TimeSpan.Parse("0:" + track)) // add hours otherwise we would need ParseExact()
.Aggregate((t1, t2) => t1 + t2); // TimeSpan.Zero is default starting value in LINQ