If I want to filter a list of objects against a specific id, I can do this:
list.Where(r => r.Id == idToCompare);
What if, instead of a single idToCompare
, I have a list of Ids to compare against?
What is the syntax for comparing against a predefined list? Something like:
int[] listofIds = GetListofIds();
list.Where(r => r.Id "in listofIds");
If listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.
You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
var query = list.Where(r => listofIds.Any(id => id == r.Id));
Another approach, useful if the listOfIds array is large:
HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));
You can use the Contains() extension method:
list.Where(r => listofIds.Contains(r.Id))
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With