C#中两个异构列表的交集
本文关键字:列表 异构 两个 | 更新日期: 2023-09-27 18:25:44
我想得到两个列表的交集:GameObject的列表和Realproperty的列表。并且在类型为list<地段>。Lot是GameObject 的成员
class GameObject
{
public string m_lotName;
public Lot m_lot;
//other members
}
class Lot
{
public string m_lotName;
//other members
}
class RealProperty
{
public string m_name;
//other members
}
List<GameObject> allLots = getAllLots();
List<RealProperty> soldRealProperties = getSoldRealProperties();
我想要一个列表<Lot>,这将是:列表<GameObject>由列表过滤<RealProperty>其中对于列表<GameObject>我们测试GameObject.m.lot.m_lotName是否存在于列表<RealProperty>元素。
看来LINQ使成为可能
我试过这样的东西:
List<Lot> soldLots = allLots
.Select(a => a.GetComponent<Lot>().m_lotName)
.Where(u => allLots
.Select(l => l.m_lot.m_lotName)
.Intersect(soldRealProperties
.Select(l2 => l2.m_name))
);
但我遇到了很多错误,比如这样一个:
Type `string' does not contain a definition for `m_name' and no extension method `m_name' of type `string' could be found (are you missing a using directive or an assembly reference?)
Type `System.Collections.Generic.IEnumerable<string>' does not contain a member `Contains' and the best extension method overload `System.Linq.Queryable.Contains<object>(this System.Linq.IQueryable<object>, object)' has some invalid arguments
Extension method instance type `System.Collections.Generic.IEnumerable<string>' cannot be converted to `System.Linq.IQueryable<object>'
有没有一种简单的方法可以得到两个异构列表的交集?
您可以使用Enumerable.Join
:
var intersecting = from game in allLots
join realProp in soldRealProperties
on game.m_lotName equals realProp.m_name
select game.m_lot;
List<Lot> soldLots = intersecting.ToList();