【问题标题】:Construct a LINQ query to return an item from a List that is related by one property to other members but which differs by a second property构造一个 LINQ 查询以从列表中返回一个项目,该项目通过一个属性与其他成员相关,但与第二个属性不同
【发布时间】:2014-10-04 23:20:30
【问题描述】:

所以我有一个对象列表,我们称它们为大象。

每个大象对象都有一个名为 ClonedFrom 的属性。这是 Elephant 类型,用于指向在图像中创建此新对象的对象。

Elephant 类还有一个名为 HasTrunk 的属性,它的类型为 bool。

所以:

public class Elephant
{
  public Elephant ClonedFrom { get; set; }
  public  bool     HasTrunk { get; set; }
}

我们有

   List<Elephant> herd

我想要一个 LINQ 查询,该查询将返回具有 false HasTrunk 属性但 ClonedFrom 属性值等于同一列表中 HasTrunk 属性设置为 true 的另一个 Elephant 的任何大象。

例如,克隆大象 A 以创建新的大象 B 和 C

B 和 C 都存在于 herd List 中,并且都具有相同的 ClonedFrom 属性值 (A)。 B 将 HasTrunk 设置为 false,而 C 将 hasTrunk 设置为 true。

我想要一个返回 B 的查询。

(注意:A 是否在列表中并不重要)

【问题讨论】:

  • herd.Where(elephant =&gt; !elephant.HasTrunk &amp;&amp; herd.Where(elephant2 =&gt; elephant2.HasTrunk).Contains(elephant2 =&gt; elephant2.ClonedFrom == elephant.ClonedFrom));这是你的意思吗?
  • @Ofris 不会为我编译
  • 如果将Contains 更改为Any 会怎样?
  • @Ofris 现在可以编译,但对于我上面概述的测试示例,它没有返回任何内容

标签: c# linq


【解决方案1】:
List<Elephant> herd = new List<Elephant>{
    new Elephant(), new Elephant(), new Elephant(), new Elephant()
};
herd[0].HasTrunk = true;
herd[1].HasTrunk = true;
herd[2].HasTrunk = false;
herd[3].HasTrunk = false; 
herd[0].ClonedFrom = herd[0];
herd[1].ClonedFrom = new Elephant();
herd[2].ClonedFrom = herd[0];
herd[3].ClonedFrom = new Elephant();
herd.Where(elephant => !elephant.HasTrunk && herd.Where(elephant2 => 
elephant2.HasTrunk).Any(elephant2 => elephant2.ClonedFrom == elephant.ClonedFrom)); //One item - elephant number 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2016-05-12
    • 2014-02-10
    • 1970-01-01
    相关资源
    最近更新 更多