What's in a String?

I've got a number of books on the go at the moment, one of them is LINQ in Action by Fabrice Marquerie et al. On page 125 the authors reveal that System.String implements IEnumerable of Char. In other words, all the groovy LINQ extension methods such as Single and Where are available on strings! For example:
string name = "Michael Jackson";
IEnumerable<Char> letterACollection = name.Where(letter => letter == 'a');
Console.Write(letterACollection.Count());
I don’t know where I’d actually need to do this, but it’s good to know that it’s there! Visual Studio doesn’t give you the LINQ extensions in IntelliSense on strings because that would be confusing.

LINQ in Action is quite wordy and discusses the theory and reasons for LINQ. I am enjoying it, but if you’re looking for a running start I’d recommend Pro LINQ by Joseph Rattz Jr which has a code sample on page 1.

Comments