首页 文章

如何仅使用唯一的电子邮件字段选择数据?

提问于
浏览
1

我需要从表中选择数据 . 数据具有电子邮件字段,该字段不是唯一的 . 现在我只想选择带有同类电子邮件的第一个项目而忽略其他项目 .

我试过了:

var users = _context.Appointments.Where(p => (p.userId == userId))
            .Select(p => new MyUserModel
            {
                Id = p.Id,
                Email = p.User.Email
            });

return users.ToList();

我想使用 Distinct() ,但我的元素不是唯一的,它们有不同的 id .

我该怎么做呢?

1 回答

  • 1

    但是,如果重复此字段,则不需要选择此元素

    您可以按电子邮件进行分组,然后执行过滤器以保留不通过电子邮件重复的对象,然后使用当前逻辑进行操作 . 例:

    var users = _context.Appointments
                    .Where(p => p.userId == userId)
                    .GroupBy(p => p.User.Email) 
                    .Where(g => g.Count() == 1) // if there is only one object with this email, then retain it otherwise discard it
                    .Select(g => g.First())
                    .Select(p => new MyUserModel
                    {
                        Id = p.Id,
                        ...
                        Email = p.User.Email
                        ...
                    });
    
    return users.ToList();
    

相关问题