简体   繁体   中英

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

I have the following linq query

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

In the example above, i have trainingusers and delegatesToBeReminded list. i want to retrieve the matching record found in trainingusers and create custom type, with fullname, email from trainingusers and additional property from delegatesTobeReminded.

Can anyone help me how to do this?

Can i use something like this?

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

Thanks

Easiest would be to use a join, as you suggested:

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

(Or you can write the equivalent in linq query syntax, as you did).

Another way is to rewrite this in linq query syntax, using 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,
}

Note that these differ depending on what happens if there is more than one delegate for a particular user. The first creates a new RecipientDetail object for each user/delegate pair; the second creates a RecipientDetail object per user, and picks the first delegate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM