简体   繁体   中英

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

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?

听起来您需要Contains方法: var obsoleteEntities = Users.Where(x => toBeDeleted.Contains(x.Id)).ToList();

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

或者

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

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