簡體   English   中英

使用LINQ比較2列表

[英]Compare 2 List using LINQ

我有2個列表,其中包含近500k +記錄。 List <Animal> and List <Zoo>.

該模型

動物

Id
BllodType
ZooId

動物園

Z_ID
ZooName
ZooAdress

我需要編寫一個LINQ函數,它可以返回與ZooIdZ_Id )相匹配的Animals列表。

我試圖做的是:

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

它說

無法從動物轉換為動物園。

注意:由於這些列表中有500k條以上的記錄,因此我正在尋找一種優化的方法來在更短的時間內遍歷這些列表。

之所以會出現此錯誤,是因為allAnimalListAnimal的列表,而x (在LINQ選擇器中)的類型是Zoo 因此,當您執行allAnimalList.Contains(x) ,您嘗試查看Animal列表是否包含Zoo ,這會產生錯誤: Cannot convert from Animal to Zoo.

嘗試這個:

// 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();

要使用LINQ JOIN:

var matchingAnimal = from animal in allAnimalList 
                     join zoo in allZooList 
                     on animal.ZooID equals zoo.Z_ID
                     select animal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM