views:

184

answers:

1

I am just getting started with Linq, WPF and Silverlight. I am trying to display data which originates from a XML document in a DataGrid. I use a Linq query to select the objects I want and link the result to the DataGrid.

XDocument doc = GedView.GedcomConverter.ConvertToXml(new StreamReader(e.Result));
var query = from person in doc.Descendants("INDI")
            select new PersonInfo()
            {
              Id = (string)person.Attribute("Value"),
              GedcomName = (string)person.Descendants("NAME").SingleOrDefault().Attribute("Value"),
              Sex = (string)person.Descendants("SEX").SingleOrDefault().Attribute("Value"),
              BirthDate = GedcomConverter.ConvertDate(person.Descendants("BIRT").SingleOrDefault()),
              DeathDate = GedcomConverter.ConvertDate(person.Descendants("DEAT").SingleOrDefault()),
              BurialDate = GedcomConverter.ConvertDate(person.Descendants("BURI").SingleOrDefault()),
            };
DataGrid.ItemsSource = query;
DataGrid.SelectedIndex = -1;

However, when the grid is scrolled, the performance is bad. I notice that the ConvertDate method is called many times. (The ConvertDate method converts a human-readable date string into a DateTime? object.)

Why is this? I had assumed that the 'query' would be executed once and not continuously.

What would be the right way to do this? I am using a query because I will want to add some kind of filter to restrict the items in the list at a later date.

Thanks

+4  A: 

Try:-

DataGrid.ItemsSource = query.ToList();

The DataGrid is not expecting the IEnumerable that it is accessing to cause something very expensive to happen when it gets an enumerator to find items. However by passing the query itself to the DataGrid you cause the query to execute every time data grid calls GetEnumerator.

Since you want to filter at a later date you could simply re-assign the ItemsSource when you change your filter settings.

AnthonyWJones
Brilliant! That works. Thanks
paul