EN
C# / .NET - find element in List
0
points
In this article, we would like to show you how to find element in List in C#.
Quick solution:
List<string> list = new List<string> { "A1", "A2", "B1" };
string item = "A2";
bool result = list.Contains(item); // True
or:
List<string> list = new List<string> { "A1", "A2", "B1" };
string search = "A2";
int result = list.IndexOf(search); // 1
or:
List<string> list = new List<string> { "A1", "A2", "B1" };
string item = "A2";
int result = list.FindIndex(x => x == item); // 1
1. Practical example using Contains() method
In this example, we use Contains() method to check if the list contains the item.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> list = new List<string> { "A1", "A2", "B1" };
string item = "A2";
bool result = list.Contains(item);
Console.WriteLine(result);
}
}
Output:
True
2. Using IndexOf() method
In this example, we use IndexOf() method to get the index of item in the list.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> list = new List<string> { "A1", "A2", "B1" };
string search = "A2";
int result = list.IndexOf(search);
Console.WriteLine(result);
}
}
Output:
1
Note:
If there's no such item, the
IndexOf()method returns-1.
2. Using FindIndex() method
In this example, we use FindIndex() method to get the index of item in the list.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> list = new List<string> { "A1", "A2", "B1" };
string item = "A2";
int result = list.FindIndex(x => x == item);
Console.WriteLine(result);
}
}
Output:
1
Note:
If there's no such item, the
FindIndex()method returns-1.