Print Page | Close Window

how can i get the last element of a query?

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2009
Forum Discription: For .NET 3.5
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=1370
Printed Date: 28-Mar-2025 at 8:45am


Topic: how can i get the last element of a query?
Posted By: monkeyking
Subject: how can i get the last element of a query?
Date Posted: 08-Jul-2009 at 8:27pm
once I query from the DomainModelEntityManager, I get a set of data, how can i get the first and last element of that set of data?



Replies:
Posted By: GregD
Date Posted: 09-Jul-2009 at 11:44am

      var query = _mgr.Customers.OrderBy(c => c.CompanyName);
      Customer aCustomer = query.FirstOrNullEntity();
      Console.WriteLine("First customer: {0}", aCustomer.CompanyName );
      Customer anotherCustomer = query.ToList().LastOrDefault();
      Console.WriteLine("Last customer: {0}", anotherCustomer.CompanyName);



The query must be forced to execute immediately for LastOrDefault(); hence the ToList() call for that one.




Posted By: monkeyking
Date Posted: 09-Jul-2009 at 5:47pm
but some time I don't have 'ToList()' method, how can I make it appear? it only has 'ToHashSet()' and others, no 'ToList()'!


Posted By: Suah
Date Posted: 19-Jul-2009 at 5:37pm
using System.Collections.Generic;
so it will appear , you may like to learn more csharp basic stuff


Posted By: monkeyking
Date Posted: 20-Jul-2009 at 7:08pm
i think this is advanced knowledge. thanks for replying


Posted By: monkeyking
Date Posted: 29-Jul-2009 at 4:47pm
no, I don't think that's soluction, even I include System.Collections.Generic, it still doesn't have 'ToList()' method.


Posted By: GregD
Date Posted: 30-Jul-2009 at 2:49pm
Originally posted by monkeyking

no, I don't think that's soluction, even I include System.Collections.Generic, it still doesn't have 'ToList()' method.


You need to reference the System.Core assembly in your project, and add using statements for System.Linq and System.Collections.Generic to your code file.

ToList() is required by the IEnumerable<T> interface (which is defined in System.Collections.Generic); therefore, any type that implements IEnumerable<T> will have an implementation of ToList().  This is true of our EntityQuery<T>. However, as you apply extension methods to a query, most such methods return a new query (using the prior one as input), and sometimes the return type can change.  But anything that's an IEnumerable<T> (this includes EntityQuery<T>, IEntityQuery<T>, and IQueryable<T>) should provide ToList().

Note that under certain circumstances you can get the non-generic IEnumerable instead of IEnumerable<T>. In those cases you may be able to call the Cast() method on the IEnumerable to cast it to an IEnumerable<T>, which will have ToList().




Print Page | Close Window