Using System.Uri’s Segments property and List().ForEach
Posted by fr3dr1k | Filed under C#
You know the feeling when you see someone use a property and you go, nice, I never knew that. Well last night that happened to me after reading Scott Hanselman’s article on Windows Powershell. In the article he created a script that automatically downloaded his podcasts. To do this he use the System.Uri class which has a property called Segments. Segments returns a string array which consists of elements in a Uri separated by a forward slash ‘/’. So lets say you have this url:
http://developer.yahoo.com/yap/guide/caja-support.html
You could then use System.Uri to get all the bits in the Uri like this:
Uri url = new Uri("http://developer.yahoo.com/yap/guide/caja-support.html");
string[] arrUri = url.Segments;
var item = from u in arrUri
select u;
foreach (string s in item)
{
Console.WriteLine(s);
}
Something else I started doing or using yesterday is the ToList().ForEach delegate method. I noticed it in the LinqToTwitter api:
var twitterTrends = from trends in tCtx.Trends
select trends;
twitterTrends.ToList().ForEach(t =>
Console.WriteLine(t.Query));
The ForEach works on a list as well, so if you take the same code I wrote earlier using a foreach loop for the Uri segments you can rewrite that as:
item.ToList().ForEach(s => Console.WriteLine(s));
The variable s is an anonymous type so it infers from the type what type it is. That is shorter code, not sure if its more efficient, but it sure looks nicer.
