LINQ, group by, and WPF Data Binding - CodePr...

来源:百度文库 编辑:神马文学网 时间:2024/07/03 08:03:57
7,104,356 members and growing! (14,151 online) dnstwjc | Settings | Watched Items | Bookmarks | My Articles | Sign out Platforms, Frameworks & Libraries » Windows Presentation Foundation » Data Binding     Beginner License: The Code Project Open License (CPOL)

LINQ, group by, and WPF Data Binding

By r.stropek

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. C# (C#1.0, C#2.0, C#3.0), Windows (WinXP, Vista), .NET (.NET3.0, .NET3.5), WPF, LINQ, Silverlight, Dev Revision: 2 (See All) Posted: 14 Oct 2008 Views: 15,713 Bookmarked: 19 times Announcements Write an iPhone Tutorial, Win an iPad Local Government Windows Azure Competition VS2010 Tech Summit Free, on-demand Monthly Competition The Daily Insider Google ditches Windows on security concerns Daily IT news: Signup now. ArticlesDesktop DevelopmentButton ControlsClipboardCombo & List BoxesDialogs and WindowsDesktop GadgetsDocument / ViewEdit ControlsFiles and FoldersGrid & Data ControlsList ControlsMenusMiscellaneousPrintingProgress ControlsSelection ControlsShell and IE programmingSmart ClientSplitter WindowsStatic & Panel ControlsStatus BarTabs & Property PagesToolbars & Docking windowsTree ControlsWeb DevelopmentAjaxApplications & ToolsASPASP.NETASP.NET ControlsATL ServerCachingCharts, Graphs and ImagesClient side scriptingCustom ControlsHTML / CSSISAPISite & Server ManagementSession StateSilverlightTrace and LogsUser ControlsValidationView StateWAP / WMLWeb SecurityWeb ServicesPHPMobile DevelopmentiPhoneAndroidWindows MobilePalmMiscellaneousBlackBerryEnterprise SystemsContent Management ServerMicrosoft BizTalk ServerMicrosoft ExchangeOffice DevelopmentSharePoint ServerDatabaseDatabaseSQL Reporting ServicesMultimediaAudio and VideoDirectXGDIGDI+General GraphicsOpenGLLanguagesC / C++ LanguageC++ / CLIC#MSILVBScriptVB.NETVB6 InteropOther .NET LanguagesXMLJavaPlatforms, Frameworks & LibrariesATLMFCSTLWTLCOM / COM+.NET FrameworkWin32/64 SDK & OSVista APIVista SecurityCross PlatformGame DevelopmentMobile DevelopmentWindows CardSpaceWindows Communication FoundationWindows Presentation FoundationWindows Workflow FoundationLibrariesWindows PowershellLINQAzureGeneral ProgrammingAlgorithms & RecipesBugs & WorkaroundsCollectionsCryptography & SecurityDate and TimeDLLs & AssembliesException HandlingLocalisationMacros and Add-insProgramming TipsString handlingInternet / NetworkThreads, Processes & IPCWinHelp / HTMLHelpUncategorised Quick AnswersParallel ProgrammingUncategorised Tips and TricksGraphics / DesignExpressionUsabilityDevelopment LifecycleDebug TipsDesign and ArchitectureInstallationWork IssuesTesting and QACode GenerationGeneral ReadingBook ChaptersBook ReviewsHardware ReviewsInterviewsScrapbookHardware & SystemUncategorised Technical BlogsCodeProject FAQsThird Party ProductsProduct ShowcaseSolution CenterMentor ResourcesAuthor ResourcesServicesProduct CatalogJob BoardCodeProject VS2008 AddinFeature ZonesProduct ShowcaseWhitePapers / Webcasts.NET Dev LibraryASP.NET 4 Web Hosting  
Search    
Advanced Search
Add to IE Search Print Friendly   Share Digg Del.icio.us Google Windows Live Technorati Blink Facebook Furl Simpy Reddit Newsvine Stumbleupon Mr. Wong Send as Email     Bookmark   Discuss   Report   6 votes for this article. Popularity: 3.50 Rating: 4.50 out of 5
1
2
3
4
5 Is your email address OK? You are signed up for our newsletters but your email address is either unconfirmed, or has not been reconfirmed in a long time. Please click here to have a confirmation email sent so we can confirm your email address and start sending you newsletters again. Alternatively, you can update your subscriptions.
  • Download source code - 1.61 KB

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:

Collapse Copy Code
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:

Collapse Copy Code
var data = new List(){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:

Collapse Copy Code
var result =from d in datagroup d by new { d.PID, d.Desc } into pgselect 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. 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:

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:

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

Collapse Copy Code
<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:

Collapse Copy Code
var result =from d in datagroup d by new { d.PID, d.Desc } into pgselect 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:

Collapse Copy Code
<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)

About the Author

r.stropek


Member 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". So today we work as IT consultants and software developers. If you want to know more about our companies or check out my blogs at http://www.software-architects.com and http://www.cubido.at (German) or take a look at my profile in XING (https://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.
Company: software architects og Location: Austria
Article Top Rate this article for us!   Poor Excellent Your reason for this vote:  FAQ 
 
Noise Tolerance  Layout  Per page   
New Message Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh) FirstPrevNext LINQ Group By fedens 7:08 3 Feb '09   This is great, but how would you capture changes if the data source changes? My collection of business objects is an ObservableCollection with dependency objects containing dependency properties.... if one of these properties change or another dependency object is added to the collection the linq query doesn't re-select the data on it's own, right?
Reply·Email·View Thread·PermaLink·Bookmark Rate this message: 1 2 3 4 5 good Zajda82 15:49 15 Oct '08   Nice idea for an article Rainer. You got my 5, keep going.
Reply·Email·View Thread·PermaLink·Bookmark 5.00/5 (1 vote) Rate this message: 1 2 3 4 5 Last Visit: 9:00 6 Jun '10     Last Update: 10:39 6 Jun '10 1

General    News    Question    Answer    Joke    Rant    Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 14 Oct 2008
Editor: Smitha Vijayan
Copyright 2008 by r.stropek
Everything else Copyright © CodeProject, 1999-2010
Web22 | Advertise on the Code Project