Linq to SQL: DISTINCT with Anonymous Types

£可爱£侵袭症+ 提交于 2019-12-03 21:47:03
dgIPs.DataSource = 
    from act in Master.dc.Activities
    where act.Session.UID == Master.u.ID
    group act by act.Session.IP.Address into g
    let ip = g.First().Session.IP
    select new
    {
      Address = ip.Address,
      Domain = ip.Domain,
      FirstAccess = ip.FirstAccess,
      LastAccess = ip.LastAccess,
      IsSpider = ip.isSpider,
      NumberProblems = ip.NumProblems,
      NumberSessions = ip.Sessions.Count()
    };

Or:

dgIPs.DataSource = 
    from act in Master.dc.Activities
    where act.Session.UID == Master.u.ID
    group act.Session.IP by act.Session.IP.Address into g
    let ip = g.First()
    select new
    {
      Address = ip.Address,
      Domain = ip.Domain,
      FirstAccess = ip.FirstAccess,
      LastAccess = ip.LastAccess,
      IsSpider = ip.isSpider,
      NumberProblems = ip.NumProblems,
      NumberSessions = ip.Sessions.Count()
    };

One of the overloads of Enumerable.Distinct accepts an IEqualityComparer instance. Simply write a class that implements IEqualityComparer and which only compares the two Address properties.

Unfortunately, you'll have to give a name to the anonymous class you're using.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!