在C#列表中查找特定元素

设置列表-

List<int> myList = new List<int>() {
   5,
   10,
   17,
   19,
   23,
   33
};

假设您需要找到一个可以被2整除的元素。为此,请使用Find()方法-

int val = myList.Find(item => item % 2 == 0);

这是完整的代码-

示例

using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      List<int> myList = new List<int>() {
         5,
         10,
         17,
         19,
         23,
         33
      };
      Console.WriteLine("List: ");
      foreach(int i in myList) {
         Console.WriteLine(i);
      }
      int val = myList.Find(item => item % 2 == 0);
      Console.WriteLine("Element that divides by zero: "+val);
   }
}

输出结果

List:
5
10
17
19
23
33
Element that divides by zero: 10