An example of grouping and joining collections in .NET: calculate total scores by student and subject

Imagine that we have two collections. First we have a student collection with IDs and names. Then we also have a collection that holds the scores the students got in various subjects on several occasions. This latter collection also holds a reference to a student by the student ID. The goal is to join the two collections and calculate the total score of each student by subject.

There are various ways to solve this problem. The goal of this post is to show an example of using the LINQ GroupBy and GroupJoin operators to build an object with the information we need.

Read more of this post

Converting a sequence of objects into a Lookup with LINQ C#

A Lookup in .NET is one of the lesser known data structures. It is similar to a Dictionary but the keys are not unique. You can insert multiple elements for the same key.

Say you have the following object and collection:

Read more of this post

LINQ to XML techniques: adding a processing instruction

In this post we saw how to add a declaration to an XML document. A well-formatted XML document starts with a declaration whose main function is to declare formally that the upcoming document is of the XML type. The XDeclaration object helps us to easily add a declaration to an XML document. Note that the XDocument.ToString method does not print the declaration for some reason so we need to print it separately if needed.

In this post we’ll see how to add a processing instruction to an XML document.

Read more of this post

LINQ to XML techniques: adding a declaration

In this post we saw how to add a namespace to an XML document. A namespace in XML is similar to the namespace in a programming language. It helps to avoid name clashes among nodes that can have similar names, like “Customer” which is quite a common domain. The fully qualified name of a node will be the namespace and the node name.

In this post we’ll see how to add a declaration to an XML document.

Read more of this post

LINQ to XML techniques: adding a namespace

In this post we built a very simple XML document using LINQ to XML. We saw the 3 most frequently used objects in the System.Xml.Linq namespace: XDocument, XElement and XAttribute. These objects and their constructors allow the creation of XML documents in a more fluent fashion than it was possible with the original XML related objects in the System.Xml namespace.

In this post we’ll see how to add a namespace to an XML document.

Read more of this post

Grouping elements in LINQ .NET using GroupBy and an EqualityComparer

The GroupBy operator has the same function as GROUP BY in SQL: group elements in a sequence by a common key. The GroupBy operator comes with 8 different signatures. Each returns a sequence consisting of objects that implement the IGrouping interface of type K – the key type – and T – the type of the objects in the sequence. IGrouping implements IEnumerable of T. So when we iterate through the result the we can first look at the outer sequence of keys and then the inner sequence of each object with that key.

The simplest version of GroupBy accepts a Func delegate of T and K, which acts as the key selector. It will compare the objects in the sequence using a default comparer. E.g. if you want to group the objects by their integer IDs then you can let the default comparer do its job. Another version of GroupBy lets you supply your own comparer to define a custom grouping or if the Key is an object where you want to define your own rules for equality.

We’ll need an example sequence which has an ID. In the posts on LINQ we often take the following collections for the demos:

Read more of this post

LINQ to XML techniques: building a basic XML document

XML may have fallen out of use compared to JSON recently but it still has a couple of good features, such as schema and namespace support. It provides the basis for standards such as XHTML, SVG, MathML and many others. The web is full of resources that discuss the pros and cons of XML and JSON, here are a few of them:

So from time to time you may still be exposed to XML in a .NET project. The System.Xml namespace offers classes with which you can build XML documents. Examples includes XmlDocument, XmlElement and XmlAttribute. However, there’s a more fluent and modern way of working with XML in code. LINQ to XML is located in the System.Xml.Linq namespace and it offers a very good library to build, modify and consume XML documents. Let’s start off with the most basic objects:

Read more of this post

Deferred execution in parallel LINQ in .NET C#

If you are familiar with LINQ then you are probably aware of the notion of deferred execution: queries are not carried out until they are needed. This is not different in parallel LINQ either. Let’s see an example:

Set up a data source:

int[] integerArray = new int[100];
for (int i = 0; i < integerArray.Length; i++)
{
	integerArray[i] = i;
}

Define a parallel query:

IEnumerable<double> results =
	integerArray.AsParallel().Select(item =>
	{
		return Math.Sqrt(item);
	});

The query has not been carried out at this point. It is carried out when the following foreach loop starts:

double sum = 0;
foreach (double result in results)
{
	sum += result;
}
Console.WriteLine("Total {0}", sum);

You can force query execution with the same extension methods as in “normal” LINQ, such as ToList, ToArray etc.:

IEnumerable<double> results =
	integerArray.AsParallel().Select(item =>
	{
		return Math.Sqrt(item);
	}).ToList();

In this case the query is executed as soon as it has been defined.

View the list of posts on the Task Parallel Library here.

Creating an empty sequence using the Empty operator in LINQ

You can create an empty sequence of a type using the Empty operator in Linq. Its usage is very simple:

IEnumerable<string> emptyStringSequence = Enumerable.Empty<string>();

This creates a sequence of strings consisting of 0 elements.

Joining unique values from two sequences with the LINQ Union operator

Say you have two sequences of the same object type:

string[] first = new string[] {"hello", "hi", "good evening", "good day", "good morning", "goodbye" };
string[] second = new string[] {"whatsup", "how are you", "hello", "bye", "hi"};

You’d then like to join the two sequences containing the values from both but filtering out duplicates. Here’s how to achieve that with the first prototype of the LINQ Union operator:

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.