UndeadBob
UndeadBob

Reputation: 1129

List of TimeSpan to String Array using LINQ

I currently have:

List<TimeSpan> times = new List<TimeSpan>();
   // ... setup the thousands of times ...
string[] timeStrings = new string[times.Count];
for (int i = 0; i < times.Count; i++)
   timeStrings[i] = times[i].ToString("mm.ss");

I feel like there should be an easy way to do this in LINQ, but I can't find it. I got close with times.Select(s => s.ToString("mm.ss").ToArray()), but it just got the first element.

Side note: Are there any good LINQ tutorials out there?

Upvotes: 0

Views: 2207

Answers (4)

evanmcdonnal
evanmcdonnal

Reputation: 48116

This is basically right, the problem is that your ToArray is being called on the string when it should be outside of that (basically a typo);

What you have;

times.Select(s => s.ToString("mm.ss").ToArray())

what you should have;

times.Select(s => s.ToString("mm.ss")).ToArray();

Upvotes: 2

Dave Zych
Dave Zych

Reputation: 21887

You almost had it:

var timesAsString = times.Select(s => s.ToString("mm.ss")).ToArray()

Upvotes: 5

pkr
pkr

Reputation: 1761

times.Select(s => s.ToString("mm.ss")).ToArray();

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124722

var timesAsString = times.Select(t => t.ToString("mm.ss")).ToArray();

Your ToArray call is currently on the string, not the enumerable.

Upvotes: 2

Related Questions