I'm attempting to compare list of ints to a list of objects. to see if one of the IDs match the a key in each object. If it does then return true, else false.
for example:
List<int> ints = new List<int> () { 1, 2, 3, 4, 5};
List<someObjectType> objects = new List<someObjectType> () { {1, 'one'}, {6, 'six'}, {45, 'forty-five'} };
(x => x.objects.any(a => ints.contains(x.id)));
However I don't know how to compare a list of ints to only one property on an object, I only know how to compare whole arrays to each other.
Are you looking for something like that?
List<int> ints = new List<int> () { 1, 2, 3, 4, 5};
// For better performance when "ints" is long
HashSet<int> ids = new HashSet<int>(ints);
List<someObjectType> objects = new List<someObjectType> () {
{1, "one"}, {6, "six"}, {45, "forty-five"} };
// if any is matched?
boolean any = objects
.Any(item => ids.Contains(item.id));
// All that match
var objectsThatMatch = objects
.Where(item => ids.Contains(item.id));
Your pseudo-code is pretty much there (though with Where
instead of Any
)...
var objectsWithIds = objects.Where(o => ints.Contains(o.Id));
Which makes me suspect this isn't what you are after...
Another way is using Intersect
, but you need to translate them both into an IEnumerable<>
of the same type.
var intersectionOfIds = objects.Select(_ => _.Id).Intersect(ints);
But this only gets you a list of Ids that are in both lists, not the objects themselves, which you would then need to go and find again.
Instead of object
, you could use the keyword dynamic
, but an even better solution would be to use some static type (if possible).
You can use dynamic
like a dictionary, the added link will provide you with some great examples.
我离得很近
(x => x.objects.any(a => ints.contains(a.id)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.