Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Friday, September 5, 2008

Sorting a Dictionary by its value

There are a number of ways of sorting a generic dictionary, and searching the net will result in a lot of painful 2.0 approaches. as of .Net 3.5 the two approaches are:


var byteOcccurance = new Dictionary<byte, int>();
// populate byteOccurrance
foreach (byte b in bytes)
{
if (!byteOcccurance.ContainsKey(b))
byteOcccurance.Add(b, 0);

byteOcccurance[b]++;
}
// draw histogram
foreach (var entry in byteOcccurance.OrderByDescending(entry => entry.Value))
Console.WriteLine("{0,3} {1} {2}",
entry.Key, entry.Value, new String('*', entry.Value / 10));

// or using LINQ

foreach (var entry in from pair in byteOcccurance orderby pair.Value ascending select pair)
Console.WriteLine("{0,3} {1} {2}",
entry.Key, entry.Value, new String('*', entry.Value / 10));

Thursday, August 7, 2008

LINQ for XML


var xml = XElement.Load (@"test.XML");
XNamespace ns = "http://test.com/stuff"

var query =
from node in xml.DescendantsAndSelf()
group node by node.Name into groupedNode
select new
{
Name = groupedNode.Key,
Occurs = groupedNode.Count()
};

query.Dump();


var
countryCrossTabulation =
from country in xml.DescendantsAndSelf(ns + "COUNTRY_NAME")
group country by country.Value into countryCrosstab
orderby countryCrosstab.Count() descending
select new
{
Name = countryCrosstab.Key,
Occurs = countryCrosstab.Count()
};

countryCrossTabulation.Dump()


Wednesday, August 6, 2008

What goes plinq plinq fizz?

Got data that needs to be processed with LINQ, maybe a database or XML file?
LINQPad

LINQPad