区别在于sql server中的两个字段:.NET

时间:2018-03-28 09:09:34

标签: c# sql-server asp.net-mvc group-by distinct

我正在尝试根据这两个字段获取表中唯一的记录。表结构是;

enter image description here

我在下面的查询中遇到的问题;

var dept = db.Departments.Where(x => x.LeadBy == SessionManager.CurrentUser.EmployeeId).FirstOrDefault();

var teams = db.Teams.Where(x => x.DeptID == dept.DepartmentId);

List<Employee> refinedEmpList = new List<Employee>();
var empList = db.Employees.ToList();
foreach (var v in teams)
{
    foreach (var c in empList)
    {
        if (v.TeamID == c.TeamId)
        {
            refinedEmpList.Add(c);
        }
    }
}

var CronRep = db.CronReports.ToList();
List<CronReport> EmpList = new List<CronReport>();
foreach (var v in refinedEmpList)
{
    foreach (var c in CronRep)
    {
        if (v.EmployeeId == c.EmpID)
        {
            EmpList.Add(c);
        }
    }
}

return View(EmpList.Where(x => x.Status != "Present" && x.Status != "Absent" && x.Fine != 0).ToList());

它显示了下面的dup条目;

Dup Entries

我尝试将查询更改为;

return View(EmpList.Where(x => x.Status != "Present" && x.Status != "Absent" && x.Fine != 0).GroupBy(x => x.EmpID).Select(x => x.First()).ToList());

但是这正如预期的那样只显示了如下的独特员工;

No dups but incorrect

^这显然是不正确的,因为我希望所有员工具有不同的日期时间但没有重复记录。

2 个答案:

答案 0 :(得分:3)

.GroupBy(x => new { x.Field1, x.Field2} ).Select(x => x.First()).ToList());

答案 1 :(得分:0)

您可以将此扩展方法用于将来

   public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
                Func<TSource, TKey> keySelector)
            {
                var seenKeys = new HashSet<TKey>();
                foreach (var element in source)
                    if (seenKeys.Add(keySelector(element)))
                        yield return element;
            }

使用

collection.DistinctBy(x => new {x.Field1, x.Field2}).ToList();