none
How do I run a LINQ query against an ObservableCollection

    Question

  • I have an ObservableCollection that gets populated from 'e.Results' after a WCF call.  However, upon completing the call, I only want the Top 25 objects in that collection.  I wrote a LINQ query that does exactly this (a Lambda would be fine too), but I can not cast the query results back to the ObservableCollection.  Here is what I have:

    Dim TopData = From NewData In MyObservableCollection
                  Order By NewData.PublishDate Descending
                  Take (25)
    
    'This compiles, but doesn't cast at runtime
    TwitterSearchResultData = TopData 
     Any ideas on a better way to accomplish this?  Thanks! Yes
    Thursday, June 10, 2010 5:25 PM

Answers

  • Since e.Result is a already ObservableCollection<NewData>, you just need to do this:
    ObservableCollection<NewData> TwitterSearchResultData = e.Result.OrderByDescending(d=>d,PublishDate).Take(25);
     
    Thursday, June 10, 2010 5:54 PM
  • Yes it worked well.  I did however need a custom method to convert the IEnumerable object returned from the .Take extension method back into an Observable collection.  I was able to do that with the help of this link:

    IEnumerable.ToObservableCollection:

    http://smehrozalam.wordpress.com/2009/01/18/ienumerabletoobservablecollection/

    Here is the VB.NET version:

    'ToObservableCollection is a custom method from the link above
    SearchResultData = ToObservableCollection(e.Result.OrderByDescending(Function(d) d.PublishDate).Take(25))
    
     
    Thursday, June 24, 2010 4:39 PM

All replies

  • TwitterSearchResultData = new ObservableCollection<YourClass>(TopData);

    These forums totally and completely SUCK if you use Chrome.

    Thursday, June 10, 2010 5:42 PM
  • Since e.Result is a already ObservableCollection<NewData>, you just need to do this:
    ObservableCollection<NewData> TwitterSearchResultData = e.Result.OrderByDescending(d=>d,PublishDate).Take(25);
     
    Thursday, June 10, 2010 5:54 PM
  • Yes it worked well.  I did however need a custom method to convert the IEnumerable object returned from the .Take extension method back into an Observable collection.  I was able to do that with the help of this link:

    IEnumerable.ToObservableCollection:

    http://smehrozalam.wordpress.com/2009/01/18/ienumerabletoobservablecollection/

    Here is the VB.NET version:

    'ToObservableCollection is a custom method from the link above
    SearchResultData = ToObservableCollection(e.Result.OrderByDescending(Function(d) d.PublishDate).Take(25))
    
     
    Thursday, June 24, 2010 4:39 PM