如何在 C# 中检查一个 List 是否包含与指定条件匹配的元素?


若要检查 C# 中的 List 是否包含与指定条件匹配的元素,代码如下 −

示例

 在线演示

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 3) == 0);
   }
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(255);
      list.Add(315);
      list.Add(410);
      list.Add(500);
      list.Add(600);
      list.Add(710);
      list.Add(800);
      list.Add(1000);
      Console.WriteLine("List elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Does some elements match the predicate = "+list.Exists(demo));
   }
}

输出

这将生成以下输出 −

List elements...
255
315
410
500
600
710
800
1000
Does some elements match the predicate = True

现在让我们看另一个示例 −

示例

 在线演示

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 7) == 0);
   }
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(255);
      list.Add(310);
      list.Add(410);
      list.Add(500);
      list.Add(600);
      Console.WriteLine("List elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Does some elements match the predicate = "+list.Exists(demo));
   }
}

输出

这将生成以下输出 −

List elements...
255
310
410
500
600
Does some elements match the predicate = False

更新于: 16-12-2019

392 次浏览

开启您的职业生涯

通过完成此课程获得认证

开始
广告
© . All rights reserved.