Linq to SQL:匿名类型的DISTINCT

时间:2009-04-12 05:16:31

标签: linq-to-sql distinct anonymous-types

鉴于此代码:

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

如何仅根据不同的地址拉出Distinct()?也就是说,如果我只是添加Distinct(),它会将整行评估为不同,因此无法找到任何重复项。我想为每个act.Session.IP对象返回一行。

我已经找到了this answer,但似乎是另一种情况。此外,如果我只选择act.Session.IP,Distinct()工作正常,但它有一个我希望避免检索的列,我宁愿不必通过手动绑定我的datagrid列来完成此操作。

2 个答案:

答案 0 :(得分:3)

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

或者:

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

答案 1 :(得分:0)

Enumerable.Distinct的一个重载接受IEqualityComparer实例。只需编写一个实现IEqualityComparer的类,它只比较两个Address属性。

不幸的是,您必须为您正在使用的匿名类命名。