Click here to Skip to main content
15,880,796 members
Articles / Desktop Programming / WPF

LINQ, group by, and WPF Data Binding

Rate me:
Please Sign up or sign in to vote.
4.57/5 (8 votes)
14 Oct 2008CPOL3 min read 67.5K   601   23   2
WPF data binding works great with LINQ! This article shows how to create a hierarchical result set by using LINQ's group by clause and how to consume it in WPF data binding.

Image 1

Introduction

LINQ introduced great things to the C# programming language, things that database developers have known for years. In some areas, LINQ goes far beyond what is available from SQL. One example is the group by clause. In SQL, the result of a group operation returns a table - nothing else is possible since SQL does not know the notion of classes. In contrast, LINQ's group by operation can create hierarchical result structures. This article shows how to write a LINQ query using group by and - even more importantly - demonstrates how you can consume the result in WPF using data binding.

The LINQ Query

In the sample, we assume that we collect status events from programs running on a computer. For every event, we could collect the process ID, a process description (e.g., the file name of the exe), and the event time. The following class acts as a container for events:

C#
public class Event
{
  public int PID { get; set; }
  public string Desc { get; set; }
  public DateTime EventTime { get; set; }
}

The following line of code generates some demo data:

C#
var data = new List<Event>() 
{
  new Event() { PID = 1, Desc="Process A", EventTime = DateTime.Now.AddHours(-1) },
  new Event() { PID = 1, Desc="Process A", EventTime = DateTime.Now.AddHours(-2) },
  new Event() { PID = 2, Desc="Process B", EventTime = DateTime.Now.AddHours(-3) },
  new Event() { PID = 2, Desc="Process B", EventTime = DateTime.Now.AddHours(-4) },
  new Event() { PID = 3, Desc="Process C", EventTime = DateTime.Now.AddHours(-5) }
};

As you can see, the master data about the processes is stored multiple times (i.e., the data structure is not in normal form). Our LINQ query should return a hierarchical result in which every process is included only once. Additionally, for every process, we want to have a collection of the corresponding events. The LINQ query solving this problem looks like this:

C#
var result =
  from d in data
  group d by new { d.PID, d.Desc } into pg
  select new { Process = pg.Key, Items = pg };

Note how the group by clause is written and how the result (anonymous type) is built. The query groups the result by process ID and process description. Both fields together make up the composite group expression (new { d.PID, d.Desc }). pg is of type IGrouping<TKey, TElement>. TKey represents the group expression mentioned before. IGrouping implements IEnumerable<code>. Therefore, pg can be used in the select clause to embed the list of corresponding Event objects for each group.

Note that the anonymous type for the result contains names for each column (Process = pg.Key, Items = pg). This is important because without the names, data binding in WPF is much harder (in fact, I do not know whether it is possible without names at all).

Here is how the result looks like in the Visual Studio debugger:

Image 2

WPF Data Binding

In my example, I want to represent the hierarchical result structure in the user interface, too. Therefore, the following sample should create an expander control for each key. Inside the expander, it should display a listbox with the event details for the corresponding key. Here is a screenshot of the result I want to achieve:

LinqGroupWpfScreen.png

Using data binding to create the expander controls is quite straightforward:

XML
<Window x:Class="WpfApplication5.Window1"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="Window1" Height="300" Width="550">
<Grid>
 <ItemsControl x:Name="TopLevelListBox" ItemsSource="{Binding}">
  <ItemsControl.ItemsPanel>
   <ItemsPanelTemplate>
    <StackPanel Orientation="Horizontal" />
   </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
   <DataTemplate>
    <Expander ExpandDirection="Down" Width="175">
     <Expander.Header>
      <StackPanel Orientation="Horizontal">
       <TextBlock Text="{Binding Path=Process.PID}" Margin="0,0,5,0"/>
       <TextBlock Text="{Binding Path=Process.Desc}" />
      </StackPanel>
     </Expander.Header>
    </Expander>
   </DataTemplate>
  </ItemsControl.ItemTemplate>
 </ItemsControl>
</Grid>
</Window>

As you can see, I use a custom ItemsPanel to display the expander controls horizontally. The data template converts each result object into the expander control. To make data binding work, we must not forget to set the data context for the ItemsControl:

C#
var result =
  from d in data
  group d by new { d.PID, d.Desc } into pg
  select new { Process = pg.Key, Items = pg };

TopLevelListBox.DataContext = result;

Based on that, we can use the hierarchical result generated by the LINQ query to insert the list of events per expander control, without writing a single line of extra C# code:

XML
<Window x:Class="WpfApplication5.Window1"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="Window1" Height="300" Width="550">
<Grid>
 <ItemsControl x:Name="TopLevelListBox" ItemsSource="{Binding}">
  <ItemsControl.ItemsPanel>
   <ItemsPanelTemplate>
    <StackPanel Orientation="Horizontal" />
   </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
   <DataTemplate>
    <Expander ExpandDirection="Down" Width="175">
     <Expander.Header>
      <StackPanel Orientation="Horizontal">
       <TextBlock Text="{Binding Path=Process.PID}" Margin="0,0,5,0"/>
       <TextBlock Text="{Binding Path=Process.Desc}" />
      </StackPanel>
     </Expander.Header>
     <ListBox x:Name="SubListBox" ItemsSource="{Binding Path=Items}">
      <ListBox.ItemTemplate>
       <DataTemplate>
        <StackPanel Orientation="Horizontal">
         <TextBlock Text="{Binding Path=EventTime}" />
        </StackPanel>
       </DataTemplate>
      </ListBox.ItemTemplate>
     </ListBox>
    </Expander>
   </DataTemplate>
  </ItemsControl.ItemTemplate>
 </ItemsControl>
</Grid>
</Window>

Note that the listbox SubListBox is bound to Items. Items has been defined as a field in the result type of the LINQ query. It contains the list of events corresponding to each group key. By binding like this, we can access the properties of Event inside the DataTemplate of the listbox.

Summary

In my opinion, the important takeaways of this sample are:

  1. LINQ is a powerful tool that is not just useful in combination with databases. It makes it easier to handle in-memory object structures, too.
  2. LINQ queries can create more complex result structures than SQL.
  3. WPF data binding works great with LINQ results, even with hierarchical result structures.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
software architects
Austria Austria
Hi, my name is Rainer Stropek. I am living a small city named Traun in Austria. Since 1993 I have worked as a developer and IT consultant focusing on building database oriented solutions. After being a freelancer for more than six years I founded a small IT consulting company together with some partners in 1999. In 2007 my friend Karin and I decided that we wanted to build a business based on COTS (component off-the-shelf) software. As a result we founded "software architects" and developed the time tracking software "time cockpit" (http://www.timecockpit.com). If you want to know more about our companies check out my blogs at http://www.software-architects.com and http://www.timecockpit.com or take a look at my profile in XING (http://www.openbc.com/hp/Rainer_Stropek2/).

I graduated the Higher Technical School for MIS at Leonding (A) in 1993. After that I started to study MIS at the Johannes Kepler University Linz (A). Unfortunately I had to stop my study because at that time it was incompatible with my work. In 2005 I finally finished my BSc (Hons) in Computing at the University of Derby (UK). Currently I focus on IT consulting, development, training and giving speeches in the area of .NET and WPF, SQL Server and Data Warehousing.

Comments and Discussions

 
QuestionLINQ Group By Pin
fedens2-Feb-09 12:08
fedens2-Feb-09 12:08 
Generalgood Pin
Zajda8214-Oct-08 20:49
Zajda8214-Oct-08 20:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.