0

I have 2 list which contains close to 500k+ records. List <Animal> and List <Zoo>.

The Model

Animal

Id
BllodType
ZooId

Zoo

Z_ID
ZooName
ZooAdress

I need to write a LINQ function where it could return a List of Animals that matches the ZooId (Z_Id).

What I tried to do :

List<Animal> matchingAni= allZooList.Any(x => allAnimalList.Contains(x));

It says

Cannot convert from Animal to Zoo.

Note: Since, I have 500k+ records in these Lists, I am looking for a optimized way to traverse these list in lesser time.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Illep
  • 16,375
  • 46
  • 171
  • 302

1 Answers1

-1

You are getting that error because allAnimalList is a list of Animal, while x (in the LINQ selector) is of type Zoo. Therefore when you do allAnimalList.Contains(x), you are trying to see if an Animal list contains a Zoo, which produces the error: Cannot convert from Animal to Zoo.

Try this:

// Use a hashset to make .Contains() an O(1) operation
var zooIDs = new HashSet<int>(from zoo in allZooList select zoo.Z_ID);
List<Animal> matchingAnimal = allAnimalList.Where(animal => zooIDs.Contains(animal.ZooID)).ToList();

To use a LINQ JOIN:

var matchingAnimal = from animal in allAnimalList 
                     join zoo in allZooList 
                     on animal.ZooID equals zoo.Z_ID
                     select animal
Sean Sailer
  • 343
  • 1
  • 12
  • 1
    How can I do this with a JOIN ? – Illep Apr 24 '19 at 16:15
  • 2
    `ConvertAll` already returns a List, calling `.ToList()` isn't necessary. – Rand Random Apr 24 '19 at 16:16
  • 1
    A little warning about performance, since OP mentions his list has 500k+ entries, you should consider using a `HashSet` for your `.Contains` approach. Calling 500k+ times `Contains` on a 500k+ `List` will be very very slow. – Rand Random Apr 24 '19 at 16:18
  • @RandRandom thank you for your comments, I agree with you hash set approach – Sean Sailer Apr 24 '19 at 16:21
  • In terms if performance what you suggest ? Should I go with the HashSet approach or the Join ? – Illep Apr 24 '19 at 16:30
  • @Illep If these lists are already in memory (I assume they are, given your example), I would suggest using the first method. If these records are stored in a database, and you are retrieving them, then I would prefer the second method as LINQ/SQL will optimize the query. – Sean Sailer Apr 24 '19 at 16:31