views:

521

answers:

2

Hi,

With class RoleRecord (Guid RoleId, string RoleName,...) I am trying to get a new list of Name where the RoleId matches a list of Guid

IEnumerable<RoleRecord> roles;
IEnumerable<Guid> roleIds;

I was thinking about avoiding the nested for loops, and along the lines of :

            var query = 
            from rowA in roles
            join rowB in roleIds
            on rowA.RoleId equals rowB.????
            select { rowA.RoleName };

I tried to wrap the guid in a class too, but cant even build it because the syntax is wrong. Any ideas? Thanks

+2  A: 

Give this a try:

var query = 
            from rowA in roles
      where roleIds.Contains(rowA.RoleId)
            select  rowA.RoleName;
Jeremy
works fine, thanks
CRice
+2  A: 

I would personally not use Jeremy's answer if you've got a significant number of Guids. If a join is what you really want to express - you just need:

var query = from rowA in roles
            join rowB in roleIds on rowA.RoleId equals rowB
            select rowA.RoleName;

Alternatively, create a set of role IDs first:

HashSet<Guid> validRoleIds = new HashSet<Guid>(roleIds);
var query = from rowA in roles
            where validRoleIds.Contains(rowA.RoleId)
            select rowA.RoleName;

The advantage is that then you don't need to do a linear search through every valid role ID for every role. That's not an issue if you know you don't have many roles or role IDs, but generally a hashing approach will be more effective.

Note that the join will use a hash as well internally.

Jon Skeet
Appreciate the reply, thanks. Am pretty new to linq but liking it more and more.
CRice