Hi I have a collection of objects:
MyClasss{
int Id,
int ?OtherId
}
I want to take do sth like:
collection.Where(x.Id == y.OtherId).
Ho to perform it in linq?
CodePudding user response:
I think you're looking for:
collection.Where(x => collection.Any(y => x.Id == y.OtherId));
Be aware that this will also pull out ones where the OtherId is equal to the Id on the same object.
CodePudding user response:
I think your problem is that Id
is an int, while OtherId
is a nullable int.
You have a sequence of objects of MyClass
, and you want to keep only those objects where "Id equals OtherId". Or to be precise:
Keep only those objects where OtherId is not null, and OtherId == Id.
The easiest method would be:
IEnumerable<MyClass> myCollection = ...
IEnumerable<MyClass> result = myCollection
.Where(myClass => myClass.OtherId.HasValue && myClass.Value == myClass.Id);