0

我是一个新手实习生,我保证我已经对此进行了彻底的研究并尝试了许多不同的东西。以下 linq 查询有效,但我想按姓氏和名字对行进行分组,然后只显示出现多次的行。当我取消注释 group by 语句时,下面的所有别名都无法识别,并且将它们更改为实际的 db.table 名称也无济于事。

 var query = from emps in db.Employees

              join c in db.Cards on emps.SbiID equals c.SbiID

              where c.StateID == 0 && c.CardNumberNumeric > 100000

             //group emps by new {emps.Surname, emps.Name}; 

             //orderby grp.Count()  // something like 'where grp.Count > 1

              select new 
              { 

                  Surname = emps.Surname,
                  Name = emps.Name,
                  CorpID = emps.Identifier,
                  CardNum = c.CardNumber,
                  CostCenter = emps.EmployeeUserField.UF13,
                  Supervisor = (from e in db.Employees
                               where                                                  
                               e.Identifier.Equals(emps.EmployeeUserField.UF5)
                               select e.Surname).FirstOrDefault()
                               + ", "
                               + (from e in db.Employees
                                  where e.Identifier.Equals(emps.EmployeeUserField.UF5)
                                  select e.Name).FirstOrDefault(),

                 SupervisorID = emps.EmployeeUserField.UF5,
                 EmpCommence = emps.CommencementDateTime,
                 CardCommence = c.CommencementDateTime,
                 WorkPhone = emps.Telephone,
                 State = (from cf in db.ComboFields
                          from sp in db.StringProperties
                          where cf.ComboIndex.Equals(c.StateID)
                          && cf.StringID.Equals(sp.StringID)
                          && cf.TableName.Equals("Card")
                          && cf.FieldName.Equals("StateID")

                         select sp.DefaultValue).FirstOrDefault()                                       

             };          

 this.tagsGridView.DataSource = query;
 this.tagsGridView.DataBind();
4

1 回答 1

0

我认为你遇到的问题是你没有适当地扁平化你的团队。例如:

var duplicateEmployees = db.Employees
    .GroupBy(emp => emp, new EmployeeComparer())
    .Where(grp => grp.Count() > 1)
    .SelectMany(grp => grp.AsEnumerable());

var duplicateEmployeeInfo =
    from emps in duplicateEmployees
    join c in db.Cards on emps.SbiID equals c.SbiID
    where c.StateID == 0 && c.CardNumberNumeric > 100000
    select new
    {
        ... what to select
    };

和:

public class EmployeeComparer : IEqualityComparer<Employee>
{
    public bool Equals(Employee x, Employee y)
    {
        return x.Surname == y.Surname && x.Name == y.Name;
    }
    public int GetHashCode(Employee obj)
    {
        unchecked { return (17 * obj.Surname.GetHashCode()) ^ (23 * obj.Name.GetHashCode()); }
    }
}

这将按名称对员工进行分组,查找计数 > 1 的组,然后返回这些组的元素。不能保证性能,但这应该可以解决您的问题。

于 2013-10-04T22:20:52.493 回答