首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#中两个异构列表的交集

C#中两个异构列表的交集
EN

Stack Overflow用户
提问于 2014-10-06 11:49:48
回答 1查看 354关注 0票数 0

我想得到两个列表的交集:一个GameObject的列表和一个Realproperty的列表,并在一个新的列表中得到这个结果,这个列表的类型是List< Lot >。Lot是GameObject的成员

代码语言:javascript
复制
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< Lot >这将是以下结果的结果: List< GameObject >被List< RealProperty过滤>对于List< gameobject的每个游戏对象>我们测试gameobject.m_lot.m_lotName是否存在于List< RealProperty >元素中。

似乎LINQ让它成为可能

我试过这样的方法:

代码语言:javascript
复制
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))
                           );

但我犯了很多错误,比如:

代码语言:javascript
复制
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>'

有一种简单的方法可以得到两个异构列表的交集吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-06 11:53:59

您可以使用Enumerable.Join

代码语言:javascript
复制
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();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26215624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档