distinct with LINQ


 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();

这将产生一个列表,如果多于一个,它将打印重复,我如何使用。distinct?

请告知,谢谢

 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();

看看这个

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

您可能想看看MoreLinq中的DistinctBy方法。其中可以将lambda表达式作为参数传递。

在你的例子中,它看起来像这样:

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();

你也可以在多个属性中使用DistinctBy:

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();

顺便说一句,匿名类型实例的相等性是通过比较它们的每个属性来确定的,而不是引用比较。

我最近发现了一个关于这个话题的有趣的讨论,Anders Hejlsberg自己提出了这个问题的解决方案。

相关内容

  • 没有找到相关文章

最新更新