0

I am doing following and it works:

    var resultsHeader = (from r in o select new { 
                        OrderID  = r.OrderID,
                        subtotal = r.SubTotal,
                        city = r.orderAddress.BilltoCity
    }).Distinct().ToList();

Look at the city = r.orderAddress.BilltoCity Line, is there any way i can populate the entire object there...like this

var resultsHeader = (from r in o select new { 
                    OrderID  = r.OrderID,
                    subtotal = r.SubTotal,
                    Address = r.orderAddress
}).Distinct().ToList();

Basicly, I want to store entire OrderAddress Object into Address property, however it does not come out as Distinct object.

highwingers
  • 1,649
  • 4
  • 21
  • 39

1 Answers1

1

You can either use DistinctBy from moreLINQ:

var resultsHeader = (from r in o select new { 
                    OrderID  = r.OrderID,
                    subtotal = r.SubTotal,
                    city = r.orderAddress.BilltoCity
}).DistinctBy(x => new { x.OrderID, x.subtotal }).ToList();

or GroupBy, which is part of LINQ already:

var resultsHeader = (from r in o
                     group r by new { r.OrderIs, r.SubTotal } into g
                     select new {
                         g.Key.OrderID,
                         g.Key.SubTotal,
                         Address = g.First().orderAddress
                     }).ToList()

UPDATE

Or, you can implement Equals and GetHashCode on your Address class and use Distinct as you do now.

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263