我想获得两个列表的交集: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();
我想要一个 List&lt; Lot&gt; 将是以下结果:a List&lt; GameObject&gt; 由 List&lt;过滤RealProperty&gt; List&lt;的每个游戏对象的位置GameObject&gt; 我们测试 gameobject.m_lot.m_lotName 是否出现在 List&lt; RealProperty&gt;元素
似乎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>'
是否有一种简单的方法可以获得两个异构列表的交集?
答案 0 :(得分:3)
您可以使用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();