0
 var sourceId =
            (from workstation in db.station
             join letter in db.letter on workstation.id equals letter.Site_Id
             where ThatDate < DateTime.Now.AddYears(-1)
             select workstatio).ToList();

This produces a list which will print out repeats if more than one, how can I use .distinct?

Please advise, thanks

John
  • 3,965
  • 21
  • 77
  • 163

2 Answers2

0
 var sourceId =
            (from workstation in db.station
             join letter in db.letter on workstation.id equals letter.Site_Id
             where ThatDate < DateTime.Now.AddYears(-1)
             select workstation).Distinct().ToList();

Take a look at this

http://msdn.microsoft.com/en-us/library/bb338049.aspx

Sean Barlow
  • 588
  • 6
  • 11
0

You might want to have a look at DistinctBy method in MoreLinq. Where you can pass a lambda expression as a parameter.

In your example it would look something similar to this:

var sourceId =
        (from workstation in db.station
         join letter in db.letter on workstation.id equals letter.Site_Id
         where ThatDate < DateTime.Now.AddYears(-1)
         select workstatio).DistinctBy(ws => ws.Id).ToList();

You can also use DistinctBy with multiple properties:

var sourceId =
        (from workstation in db.station
         join letter in db.letter on workstation.id equals letter.Site_Id
         where ThatDate < DateTime.Now.AddYears(-1)
         select workstatio).DistinctBy(ws => new {Id = ws.Id, OtherProperty = ws.OtherProperty}).ToList();

Btw, instead of reference-comparing, the equality of anonymous type instances is determined by comparing each one of their properties.

I have recently found an interesting discussion around this topic where Anders Hejlsberg himself suggests the solution to this problem. You can read it here.

TKharaishvili
  • 1,997
  • 1
  • 19
  • 30