linq select objects by id when any id form the list of other objects is the same in csharp

Assuming you have a list of objects and a list of ids, you can select the objects with matching ids using LINQ's Where method and the Contains method on the list of ids.

Here is an example:

main.cs
// Define sample classes
class MyObject {
    public int Id { get; set; }
    public string Name { get; set; }
}

// Create sample data
List<MyObject> objects = new List<MyObject> {
    new MyObject { Id = 1, Name = "Object 1" },
    new MyObject { Id = 2, Name = "Object 2" },
    new MyObject { Id = 3, Name = "Object 3" },
};

List<int> ids = new List<int> { 1, 3 };

// Select objects with matching ids
var result = objects.Where(x => ids.Contains(x.Id));

// Output the result
foreach (var item in result) {
    Console.WriteLine($"{item.Id}, {item.Name}");
}
565 chars
23 lines

This will output:

main.cs
1, Object 1
3, Object 3
24 chars
3 lines

related categories

gistlibby LogSnag