Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Exist in List<string> in C#

Tags:

c#

I have to find if string exist in a list to avoid duplicates inserts: Here is example from Microsoft site:

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();

        dinosaurs.Add("Compsognathus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Oviraptor");
        dinosaurs.Add("Velociraptor");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Dilophosaurus");
        dinosaurs.Add("Gallimimus");
        dinosaurs.Add("Triceratops");

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nTrueForAll(EndsWithSaurus): {0}",
            dinosaurs.TrueForAll(EndsWithSaurus));

        Console.WriteLine("\nFind(EndsWithSaurus): {0}", 
            dinosaurs.Find(EndsWithSaurus));

        Console.WriteLine("\nFindLast(EndsWithSaurus): {0}",
            dinosaurs.FindLast(EndsWithSaurus));

        Console.WriteLine("\nFindAll(EndsWithSaurus):");
        List<string> sublist = dinosaurs.FindAll(EndsWithSaurus);

        foreach(string dinosaur in sublist)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
            "\n{0} elements removed by RemoveAll(EndsWithSaurus).", 
            dinosaurs.RemoveAll(EndsWithSaurus));

        Console.WriteLine("\nList now contains:");
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nExists(EndsWithSaurus): {0}", 
            dinosaurs.Exists(EndsWithSaurus));
    }

    // Search predicate returns true if a string ends in "saurus".
    private static bool EndsWithSaurus(String s)
    {
        return s.ToLower().EndsWith("saurus");
    }
}

Is it possible to replace EndsWithSaurus function with lambda expression? Thanks everybody for your input!! Here is a working code:

        if (dinosaurs.Any(e => e.EndsWith("saurus")))
            Console.WriteLine("saurus exists");

        if (dinosaurs.Exists(e => e.EndsWith("saurus")))
            Console.WriteLine("saurus exists");
like image 990
GenZiy Avatar asked Jun 14 '13 12:06

GenZiy


People also ask

How do you check if a string is present in a list of strings in C#?

bool b = listOfStrings. Any(s=>myString. Contains(s));

How do you check if a value exists in a list in C#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do I return a string from a list in C#?

In C# you can simply return List<string> , but you may want to return IEnumerable<string> instead as it allows for lazy evaluation. @Marc: Certainly, but if you return List<string> you don't have the option even with a lazy source.

Is item in list C#?

Check if an item is in the C# list or not. The Contains method checks if the specified item already exists in the C# List. C# List<T> class provides methods and properties to create a list of objects (classes). The Contains method checks if the specified item is already exists in the List.

What is the Exists method on the list type?

C# List Exists Method This C# example program demonstrates the Exists method on the List type. Exist returns whether a List element is found. You could use a loop and an if-statement. But the Exists method may be clearer in some program contexts. We invoke the Exists method on the List type with a lambda expression. Example.

How to check if element is in C #list using contains ()?

Example 1 – Check if Element is in C# List using Contains () In the following program, we have a list of integers. We shall check if element 68 is present in the list or not using Contains () method. As 68 is present in the list, List.Contains () method returns True.

How to test if a list element exists in Java?

We examine the Exists method on List. Exists returns whether a List element is present. We invoke this method with a lambda expression. Exists call 1 The code tests first to see if any element in the List exists that has a value greater than 10, which returns true. Exists call 2 Then it tests for values less than 7, which returns false.

What is the difference between any () and exists () in List<T>?

The difference is just the Exists () method comes from List<T> itself and the Any () is just one of the great Linq extension methods (and will require using System.Linq) Show activity on this post. You could use List.Exists () by just changing your lambda: but Any is more portable (i.e. can be used with any enumerable, not just List s.


2 Answers

Try this:

if (dinosaurs.Exists(e => e.EndsWith("saurus")))
        Console.WriteLine("saurus exists");

The answer with Any() works fine too. The difference is just the Exists() method comes from List<T> itself and the Any() is just one of the great Linq extension methods (and will require using System.Linq)

like image 131
Sevenate Avatar answered Sep 18 '22 09:09

Sevenate


Use Any:

if (dinosaurs.Any(e => e.EndsWith("saurus")))
        Console.WriteLine("saurus exists");

You could use List.Exists() by just changing your lambda:

if (dinosaurs.Exists(e => e.EndsWith("saurus"))   // == true is implied
        Console.WriteLine("saurus exists");

but Any is more portable (i.e. can be used with any enumerable, not just Lists.

like image 34
D Stanley Avatar answered Sep 18 '22 09:09

D Stanley