首页 > 解决方案 > C# Linq 检查对象列表中是否存在 INT

问题描述

我正在尝试查看对象列表中是否存在 INT 。在下面我的最佳尝试中,我创建了一个 Person 类及其成员资格列表(它们仅包含 Id)。我正在检查人员的成员资格列表中是否存在特定整数。

在下面的代码中,Person 属于 Membership id 1、3 和 4。我正在尝试创建一个 LINQ 语句,当给定一个 Integer 时,如果该整数存在于 Person 的成员资格中,它将返回一个 TRUE/FALSE 值。

我创建了两个场景:x = 4 应该返回 TRUE,而 x = 6 应该返回 FALSE,但由于某种原因,它们都返回 TRUE。

我究竟做错了什么?

public class Program
{
    public class Person {
      public int id {get;set;}
      public string first {get;set;}
      public string last {get;set;}     
      public List<Membership> memberships {get;set;}
    }

    public class Membership {
      public int id {get;set;}
    }   

    public static void Main()
    {

      Person p1 = new Person { id = 1, first = "Bill", last = "Jenkins"};
      List<Membership> lm1 =  new List<Membership>();
      lm1.Add(new Membership {id = 1});
      lm1.Add(new Membership { id = 3 });
      lm1.Add(new Membership { id = 4 });
      p1.memberships = lm1;

      int correct = 4;  /* This value exists in the Membership */
      int incorrect = 6;   /* This value does not exist in the Membership */

      bool x = p1.memberships.Select(a => a.id == correct).Any();
      bool y = p1.memberships.Select(a => a.id == incorrect).Any();

       Console.WriteLine(x.ToString());
            // Output:  True

       Console.WriteLine(y.ToString());
            // Output:  True     (This should be False)

    }
}

标签: c#listlinq

解决方案


您的代码正在将成员资格转换为 的列表bool,然后查看是否有任何成员 - 因为您有一个类似的列表:[false, false, false]. 你想要的是这样的:

bool x = p1.meberships.Any(a => a.id == correct);

推荐阅读