Linq to SQL: DISTINCT with Anonymous Types

非 Y 不嫁゛ 提交于 2020-01-01 07:28:51

问题


Given this code:

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

How do I pull the Distinct() based on distinct Address only? That is, if I simply add Distinct(), it evaluates the whole row as being distinct and thusly fails to find any duplicates. I want to return exactly one row for each act.Session.IP object.

I've already found this answer, but it seems to be a different situation. Also, Distinct() works fine if I just select act.Session.IP, but it has a column I wish to avoid retrieving and I'd rather not have to do this by manually binding my datagrid columns.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/741299/linq-to-sql-distinct-with-anonymous-types

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