简体   繁体   中英

C# Object.Equals() with multiple or conditions

How can I use the Equals method, so that it checks if the user ID equals any of the IDs in someIDs? In this case, I want to get all the users where the ID is the same as the IDs in someIDs.

List<int> someIDs = someList.Select(x => x.id).ToList();
List<User> result = allUsers.Where(x => x.id.Equals(someIDs)).ToList();

This is what works, however it is hardcoded. I want it to be similar.

List<int> someIDs = someList.Select(x => x.id).ToList();
List<User> result = allUsers.Where(x => x.id.Equals(someIDs[0]) ||
                                        x.id.Equals(someIDs[1]) ||
                                        x.id.Equals(someIDs[2])
).ToList();

You should not override Equals to provide a method for checking the id matches a list. Instead use what is already provided on an array/list

var result = allUsers.Where(x => someIDs.Contains(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