Reputation: 23
I have a task like this: Write a LINQ expression that shows how many books have been printed in each decade of the last century. The answer should be given as a sequence of objects with properties: D - decade number (1, 2, ... 10), C - number of books. And also you cannot use while, for, foreach.
There is a class
class Book {
public string Title { set; get; }
public int Year { set; get; } }
and a collection of books - books
In the beginning I did this:
var g = books.GroupBy(b => b.Year % 100 == 0 ? (b.Year == 1900 ? 1 : 10) : (b.Year % 100 - 1) / 10 + 1,
b => b.Year,
(decade, years) => new
{
D = decade,
C = years.Count()
});
But this only creates groups for existing decades from the collection, then i realised that there must be 10 groups with a D value from 1 to 10. I tried to do this, but without loops, it did not work for me. Could you tell me how this can be implemented in a group-buy, since the tasks are related to the introduction to the linq, but I could not figure it out properly.
P.S. Sorry for bad English
Upvotes: 0
Views: 53
Reputation: 186718
Well, we can create all 10
decades (to be sure that each decade is present in the answer even if there are no books printed in it)
Enumerable.Range(0, 10)
and then Count
the books in them. So, given a collection, enumeration of books
IEnumerable<Book> books = ...
var result = Enumerable
.Range(0, 10)
.Select(D => new {
D = D + 1,
C = books.Count(book => book.Year >= 1900 + D * 10 &&
book.Year < 1900 + (D + 1) * 10)
});
Upvotes: 2