Some more LINQ love

by Jon Sagara June 4, 2009 at 3:32 PM

Here's another example of how I feel LINQ improves the readability of my code. This is the before version, using standard looping to populate a list of objects:

private IEnumerable<Album> ReadAlbums(LLAlbum[] llAlbums)
{
	Album album;
	IList<Album> albums = new List<Album>(llAlbums.Length);

	foreach (LLAlbum llAlbum in llAlbums)
	{
		album = new Album()
		{
			AlbumId = llAlbum.Id
		};

		albums.Add(album);
	}

	return albums;
}

And here is the after version, using a LINQ query:

private IEnumerable<Album> ReadAlbums(LLAlbum[] llAlbums)
{
	return from llAlbum in llAlbums
		   select new Album
		   {
			   AlbumId = llAlbum.Id
		   };
}

Now, depending on your familiarity with LINQ, you may or may not agree with me, but I love it!

Tags: , ,

Blog

Project Euler: Problem 1

by Jon Sagara May 23, 2009 at 12:32 PM

I just put my son down for a nap, so since I had a little spare time, I thought I'd try my hand at Project Euler.

Problem 1 was very simple. Right off the bat, I knew how I wanted to solve it:

int sum = 0;
for (int ix = 0; ix < 1000; ix++)
{
	if (ix % 3 == 0 || ix % 5 == 0)
	{
		sum += ix;
	}
}

However, I've been reading Jon Skeet's excellent book, C# in Depth, so I wanted to see if I could solve it using LINQ:

int sum = Enumerable.Range(0, 1000)
	.Where(x => (x % 3 == 0 || x % 5 == 0))
	.Sum();

It still looks weird to me, but it works, so who am I to complain? :)

Tags: , , ,

Blog