【发布时间】:2014-11-30 16:14:50
【问题描述】:
我想获得两个列表的交集:GameObject 列表和 Realproperty 列表。并在类型为 List
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,这将是以下结果: List 由 List 对于 List 的每个游戏对象,我们测试 gameobject.m_lot.m_lotName 是否存在于 List 元素中 .
似乎 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>'
有没有一种简单的方法来获取两个异构列表的交集?
【问题讨论】:
-
你真的应该停止在你的属性名称中使用
m_前缀,这会让它非常难以阅读。 -
你在你的第一个
Select中选择了LotID,它不再是你的Lot类型的列表,它是LotID类型的列表(大概是字符串)。 -
@DavidG:对你来说什么是好的约定? mName ?
-
如果只是“姓名”,你会不会缺少一些东西?这样你就会有 Lot.Name
-
@Sean:我打错了。谢谢你的评论。我刚刚通过将 LotID 转换为 m_lotName 来纠正它