Using LINQ to filter a list of items based on those items' presence in another list

.net, .net-3.5, c#, linq

Solution

I think this is what you want.

if (list2.Any(l2c => l2c.Name == cmd.Name))
{ ... }

but you can add it to the `foreach` and avoid the `if` in your code:

foreach(Command cmd in list1.Where(l1c => list2.Any(l2c => l2c.Name == l1c.Name)))
{
    ... some code ...
}

If you control the `Command` class and can define equality in it (overriding Equals, etc), you can simply use `Intersect`:

foreach(var cmd in list1.Intersect(list2))
{ ... }

If you don't control `Command` or don't want to define equality in the class, you can still use `Intersect` with an `IEqualityComparer`

foreach(var cmd in list1.Intersect(list2, new CommandComparer()))
{ ... }

class CommandComparer : IEqualityComparer<Command>
{ ... }

Problem

I'm trying to learn LINQ by practice. This seems like a situation where I should be able to use it, but I can't quite figure out if it's possible or if I'm barking up the wrong tree. Can I achieve what's in the brackets [] with a one-liner LINQ query given the use case below? ``` List<Command> list1, list2; PopulateCommandLists(list1, list2); foreach(Command cmd in list1) { if ([cmd.Name is present as the Name in any of list2's Command objects]) { //some code. } } ```

Original source