【问题标题】:How to take elements from the same collection based on other atrributes如何根据其他属性从同一个集合中获取元素
【发布时间】:2021-12-23 08:37:08
【问题描述】:

您好,我有一个对象集合:

MyClasss{
int Id,
int ?OtherId
}

我想做某事:

collection.Where(x.Id == y.OtherId).

如何在 linq 中执行它?

【问题讨论】:

  • 首先,你尝试了什么?其次,当你说你想得到那些Id等于OtherId的东西时。您是指同一个对象,还是集合中任何对象的 Id 等于集合中任何其他对象的 OtherId?
  • 我的意思是在其他对象的 Id 上设置了 OtherId 的其他对象
  • 以下任何答案对您有用吗?

标签: linq


【解决方案1】:

我想你正在寻找:

collection.Where(x => collection.Any(y => x.Id == y.OtherId));

请注意,这也会拉出那些 OtherId 等于同一对象上的 Id 的对象。

【讨论】:

    【解决方案2】:

    我认为您的问题是 Id 是一个 int,而 OtherId 是一个可为空的 int。

    您有一个MyClass 的对象序列,并且您只想保留那些“Id 等于OtherId”的对象。或者更准确地说:

    仅保留 OtherId 不为 null 且 OtherId == Id 的对象。

    最简单的方法是:

    IEnumerable<MyClass> myCollection = ...
    
    IEnumerable<MyClass> result = myCollection
        .Where(myClass => myClass.OtherId.HasValue && myClass.Value == myClass.Id);
    

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多