.Net ramblings
# Monday, 17 September 2007
LINQ with strings
Today was the first time i used LINQ with non-database data.  I always knew you could do it but didn't realise how satisfying it would actually be to use LINQ to crunch out some results that i would otherwise have to code up in some gnarly routine involving on-the-fly DataTables and DataView filters etc.  Also, I'm mainly posting this because i can never remember the LINQ group by syntax...

i have a plain list of reference numbers, e.g. 1.a, 2.b, 3.c, 4.a, 10.d, 11.c etc.  they contain duplicates and i was asked to figure out the top 10 most popular references.  A simple regex separates out the numbers, i could also have used string.split() but regex is better in my case.  Copy each one into an array and then a simple LINQ query on the array gives me the top 10 references:
List<string> lst = new List<string>();
foreach(Match m in Regex.Matches(this.txtInput.Text, @"\w+\.\w+", RegexOptions.IgnoreCase))
var results = (from l in lst group l by l into g select new {Ref = g.Key, Total = g.Count()}).OrderByDescending(z => z.Total).Take(10);
foreach(var v in results)
this.txtOutput.Text += v.Ref + "\t" + v.Total + "\r\n";

Monday, 17 September 2007 15:01:26 (GMT Daylight Time, UTC+01:00)  #    Comments [0]  .Net General

Please login with either your OpenID above, or your details below.
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview