ERTJAIN
ERTJAIN

Reputation: 1

Get a distinct list

I want to select a distinct list.

The following code is not working:

public IQueryable<BusinessObjects.Order> GetByBusinessId(Guid Id)
    {
        rentalEntities db = DataContextFactory.CreateContext();

        List<Rental.BusinessObjects.Order> transformedList = new List<BusinessObjects.Order>();
        foreach (Rental.DataObjects.EntityModel.Order item in db.Orders.Where(x => x.BusinessID == BusinessId).ToList())
        {
            transformedList.Add(OrderMappers.ToBusinessObject(item));
        }
        return( transformedList.AsQueryable()).Distinct();
    }

Upvotes: 0

Views: 376

Answers (3)

Mike Chamberlain
Mike Chamberlain

Reputation: 42480

You might like to try the DistinctBy() extension method from the MoreLinq library. This lets you easily control the exact semantics of how two objects are compared for distinctness. For instance:

return transformedList.AsQueryable().DistinctBy(orderBO => orderBO.OrderId);

http://morelinq.googlecode.com/files/morelinq-1.0-beta.zip

Upvotes: 0

Nathan
Nathan

Reputation: 6216

Try this:

return Rental.DataObjects.EntityModel.Order item in db.Orders
  .Where(x => x.BusinessID == BusinessId)
   .Distinct()
    .Select(item => OrderMappers.ToBusinessObject(item));

This should move the distinct operation to the underlying database call as it's applied before the query is materialized - this is more efficient as the duplicate rows aren't retrieved from the database server. If for some reason you don't want to do that, then check your equals implementation (as mentioned by Sorin)

Upvotes: 1

Sorin Comanescu
Sorin Comanescu

Reputation: 4867

You may want to check how your business objects implement Equals(), my guess is they are are different even if they have (let's say) the same ID.

Upvotes: 0

Related Questions