linq select object where id is equal to any id form the other list in csharp

You can use the Where method with a condition that uses the Contains method to check if the ID of each object is present in the other list of IDs. Here's an example code:

main.cs
List<int> ids = new List<int> { 1, 3, 5, 7 };
List<MyObject> objects = GetMyObjects(); // assume this method returns a list of MyObject
List<MyObject> selectedObjects = objects.Where(obj => ids.Contains(obj.Id)).ToList();
222 chars
4 lines

In the above code, ids is the list of IDs you want to match against, GetMyObjects() is a method that returns the list of MyObjects you want to filter, and MyObject is the class that represents the objects you want to select from.

Where applies the condition ids.Contains(obj.Id) to each object in the objects list, and only those objects whose ID is present in the ids list are selected. The ToList method at the end converts the result back to a list of MyObject.

gistlibby LogSnag