Home > Software engineering >  How to write a LINQ query that will return list of entities whose ID is included in specific list?
How to write a LINQ query that will return list of entities whose ID is included in specific list?

Time:06-21

I have a list of Users.

User.cs

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

I want to create a method that will receive list of Ids. And based on that, it will create/update/delete data from User table in DB.

If I have 3 User records in DB with ids {1, 2, 3}

And my method receives List userIds = {2, 3, 5}.

Outcome should be, in DB, User table should have 2, 3, 5. So, '1' will be removed, 2 and 3 will be updated(for simplicity not mentioning how) and '5' will be added.

I take these 3 types of ids like this :

var existingUserIds = existingsUsers.Select(x=>x.Id).ToList();

var toBeDeleted = existingsUsers.Except(userIdsFromParameters).ToList();
var toBeUpdated = existingUsers.Intersect(userIdsFromParameters).ToList();
var toBeAdded = userIdsFromParameters.Except(existingUsers).ToList();

//Delete operation

    foreach (var id in toBeDeleted)
    {
        var obsoleteEntities = Users.Where(x => x.Id== id).ToList();

        if (obsoleteEntities != null)
        {
            Users.RemoveRange(obsoleteEntities);
        }
    }

That seems like a lot of operations. Same goes with updates.

Is there a way to write a LINQ query, that will give me all the users whose IDs are included in toBeDeleted list?

CodePudding user response:

var obsoleteEntities = Users.Where(x => toBeDeleted.Contains(x.Id)).ToList();

or

var obsoleteEntities = Users.Where(x => toBeDeleted.Any(tbd=>tbd==x.Id)).ToList();

CodePudding user response:

Sounds like you need the Contains method: var obsoleteEntities = Users.Where(x => toBeDeleted.Contains(x.Id)).ToList();

  • Related