【问题标题】:Compare 2 List using LINQ使用 LINQ 比较 2 个列表
【发布时间】:2019-09-13 23:55:55
【问题描述】:

我有 2 个列表,其中包含接近 500k+ 条记录。 List <Animal> and List <Zoo>.

模型

动物

Id
BllodType
ZooId

动物园

Z_ID
ZooName
ZooAdress

我需要编写一个 LINQ 函数,它可以返回与 ZooId (Z_Id) 匹配的 Animals 列表。

我想做什么:

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

上面写着

无法从动物转换为动物园。

注意:由于我在这些列表中有 500k+ 条记录,因此我正在寻找一种优化方法来在更短的时间内遍历这些列表。

【问题讨论】:

  • 你想做一个Join
  • 为什么首先需要这个?由于您使用的是实体框架 - 您的 Zoo 对象应该有一个名为 AnimalsNavigation Property ,它应该返回您想要的内容,即所有 Animals 对于那个 Zoo?!?
  • 动物和动物园之间有继承关系吗?

标签: c# entity-framework linq


【解决方案1】:

您收到该错误是因为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

【讨论】:

  • 我怎样才能用 JOIN 做到这一点?
  • ConvertAll 已经返回一个列表,不需要调用.ToList()
  • 关于性能的一点警告,因为 OP 提到他的列表有 500k+ 条目,您应该考虑为您的 .Contains 方法使用 HashSet。在 500k+ List 上调用 500k+ 次 Contains 会非常非常慢。
  • @RandRandom 谢谢你的 cmets,我同意你的哈希集方法
  • 就性能而言,您的建议是什么?我应该使用 HashSet 方法还是 Join ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多