Home > Software engineering >  How to intersect two different object collections by specific property?
How to intersect two different object collections by specific property?

Time:06-21

There are two different objects.

UserDto.cs

public Guid GradeId { get; set; }
public bool isActiveUser { get; set; }

User.cs

public Guid GradeId { get; set; }
public bool isActiveUser { get; set; }
public Guid ParentUserId { get; set; }

Both object have some data and I am trying to get intersection and update only those objects in DB.

var toBeUpdated = userDtos
  .Intersect(mapper.Map<List<User>>(users)) //USING AutoMapper here
  .ToList();


foreach (var item in toBeUpdated)
{
     userRepository.Update(item);
}

These objects must be intersected with GradeId. With the code I wrote, I am not getting any objects by that query. Example :

users :

GradeId - 1 isActive - false

userDtos :

GradId - 1 isActive - true

I want to be able to intersect these two collections by GradeId and set isActive to true(as in DTO)

CodePudding user response:

There are several ways how this can be done. The most intuitive way to find intersections of collections is to iterate over both collections in a double loop:

foreach (var dto in userDtos)
{
    foreach (var user in users)
    {
        if (user.GradeId == dto.GradeId)
        {
            // Do something work here...
            userRepository.Update(user);
        }
    }
}

You can also do the same using Linq:

IEnumerable<User> usersToUpdate =
        from dto to userDtos
        from user to users
        where user.GradeId == dto.GradeId
        select user;

foreach (var user in usersToUpdate)
{
    // Do something work here...
    userRepository.Update(user);
}

Or like this:

IEnumerable<User> usersToUpdate = userDtos
    .SelectMany(dto => users, (dto, user) => new { dto, user })
    .Where(pair => pair.user.GradeId == pair.dto.GradeId)
    .Select(pair => pair.user);

foreach (var user in usersToUpdate)
{
    // Do something work here...
    userRepository.Update(user);
}

CodePudding user response:

There is no need to use nested Foreach.

var items = userDtos.Select(x => x.GradeId)
                          .Intersect(users.Select(y => y.GradeId))
                          .ToList(); 
  • Related