Languages
[Edit]
EN

C# / .NET - find element in List

0 points
Created by:
Pearl-Hurley
559

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.

References

  1. String.Contains Method (System) | Microsoft Docs
  2. String.IndexOf Method (System) | Microsoft Docs
  3. List<T>.FindIndex Method (System.Collections.Generic) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join