C# linq 如何在满足条件时从谓词列表中获取 属性

C# linq how to get property from predicate list when condition is met

我有以下 linq 查询

var usersToNotify = trainingUsers.Where(x => delegatesToBeReminded.Any(d => d.UserGuid == x.UserGuid))
                                 .Select(x => new RecipientDetail
                                 {
                                     FullName = x.FullName,
                                     Email = x.Email,
// get property from delegatesToBeReminded
                                 })
                                 .ToList();

在上面的示例中,我有 trainingusers 和 delegatesToBeReminded 列表。我想检索在 trainingusers 中找到的匹配记录并创建自定义类型,包括来自 trainingusers 的全名、电子邮件和来自 delegatesTobeReminded 的附加 属性。

任何人都可以帮助我如何做到这一点?

我可以用这样的东西吗?

            var x = from tu in trainingUsers
                    join d in delegatesToBeReminded on tu.UserGuid equals d.UserGuid
                    select new RecipientDetail
                    {
                        FullName = tu.FullName,
                        Email = tu.Email,
                        Session = d.Session
                    };

谢谢

最简单的方法是按照您的建议使用联接:

trainingUsers.Join(
    delegatesToBeReminded,
    user => user.UserGuid,
    delegateToBeReminded => delegateToBeReminded.UserGuid,
    (user, delegateToBeReminded) => new RecipientDetail
    {
        FullName = user.FullName,
        Email = user.Email,
        Delegate = delegateToBeReminded,
    });

(或者您可以像您一样用 linq 查询语法编写等价物)。

另一种方法是在 linq 查询语法中重写它,使用 let:

from user in trainingUsers
let delegateToBeReminded = delegatesToBeReminded.FirstOrDefault(d => d.UserGuid == user.UserGuid)
where delegateToBeReminded != null
select new RecipientDetail
{
    FullName = user.FullName,
    Email = user.Email,
    Delegate = delegateToBeReminded,
}

注意这些不同取决于如果特定用户有多个委托时会发生什么。第一个为每个 user/delegate 对创建一个新的 RecipientDetail 对象;第二个为每个用户创建一个 RecipientDetail 对象,并选择第一个委托。