【问题标题】:C# Linq Check if INT exists in list of objectsC# Linq 检查对象列表中是否存在 INT
【发布时间】:2020-04-16 15:04:45
【问题描述】:

我正在尝试查看对象列表中是否存在 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)

    }
}

【问题讨论】:

  • 将选择更改为位置。例如: bool y = p1.memberships.Where(a => a.id == 不正确).Any()
  • 或者更好,p1.memberships.Any(a =&gt; a.id == incorrect)
  • 是的,最好使用 Any。谢谢乔恩·斯基特。

标签: c# list linq


【解决方案1】:

您的代码正在将成员资格转换为bool 的列表,然后查看是否有任何成员 - 就​​像您拥有的列表一样:[false, false, false]。你想要的是这样的:

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

【讨论】:

    【解决方案2】:

    您也可以在这里使用List&lt;T&gt;.Exists(Predicate&lt;T&gt;) 方法,它不需要使用System.Linq 命名空间。只需将谓词作为参数传递给它

    bool x = p1.memberships.Exists(a => a.id == correct);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 2015-11-21
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      相关资源
      最近更新 更多