Sum the number of times a digit appears in a sequence

By Peter Bromberg

This was a response to my Google+ LINQ Quiz: Write a LINQ query that provides the sum of the number of times "1" is found in the sequence 1...100.

The answer is:

var sum = Enumerable.Range(1, 100).Sum(i => i.ToString().Count(c => c == '1'));

Console.WriteLine(sum);

//Output: 21

Sum the number of times a digit appears in a sequence  (1176 Views)