【问题标题】:Intersection of two heterogeneous list in C#C#中两个异构列表的交集
【发布时间】:2014-11-30 16:14:50
【问题描述】:

我想获得两个列表的交集: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,这将是以下结果: ListList 对于 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 来纠正它

标签: c# linq list filter


【解决方案1】:

你可以使用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();

【讨论】:

  • 感谢蒂姆的回答。事实上,新的 List 需要的 Lot 是它们在 game.m_lot 中的精确副本。 “new Lot { m_lotName = game.m_lotName }” 是创建新的 Lot 并仅初始化其名称,还是创建 List 中的批次成员的副本?
  • @matt:它创建具有相同名称的新 Lot 实例。我还没有看到GameObject 具有Lot 类型的属性。然后你可以改用select game.m_lot。注意这个属性是小写的lot,是不是打错字了?
  • 感谢蒂姆。是的,这是一个错字,我刚刚改了。我现在就试试你的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
相关资源
最近更新 更多