Search code examples
c#wpfdata-bindingcollectionviewsource

Locate a record in a C# CollectionViewSource


I have a CollectionViewSource that contains a set of indexed records extracted from an MS SQL Server Table called Example using Entity framework 6.2.

Example is declared as a DbSet property of my DbContext class viz:

public virtual DbSet<Example> Examples { get; set; }  

My CollectionViewSource is:

CollectionViewSource exampleViewSource;

I can move around the collection and count the number of records it contains using the following for example:

int selectedRecordPosition = exampleViewSource.View.CurrentPosition;
exampleViewSource.View.MoveCurrentToPrevious();
int numberOfRecordsInCollectionView = exampleViewSource.View.SourceCollection.Cast<Example>().Count(); 

How can I find a particular record in the collection and set it as the record pointer's current location?

I'm looking for something like:

    var selectedObject = exampleViewSource.View.SourceCollection.Find(key1, key2);   // example pseudo code.        
    exampleViewSource.View.MoveCurrentTo(selectedObject);

key1 & key2 are the Primary access keys for the Example tables' rows.

Can anyone help please?


Solution

  • BionicCode provided a solution my question but someone must have deleted it. Based on BionicCode's answer I coded ….

    Example selectedObject = exampleViewSource.View.SourceCollection.Cast<Example>()
                             .Where(selectedRecord =>
                              selectedRecord.Column1Name == key1 && 
                              selectedRecord.Column2Name == key2)
                             .FirstOrDefault();
    if (selectedObject == null) break;
    exampleViewSource.View.MoveCurrentTo(selectedObject);
    

    The only difference is that BionicCode didn't use a Cast and his post disappeared before I could follow it exactly. Anyway, many thanks BionicCode - you got me off the hook.