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

I need to find if a line exists in the list to avoid duplicate inserts: Here is an example 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 the EndsWithSaurus function EndsWithSaurus a lambda expression? Thank you all for your input! Here is the working code:

  if (dinosaurs.Any(e => e.EndsWith("saurus"))) Console.WriteLine("saurus exists"); if (dinosaurs.Exists(e => e.EndsWith("saurus"))) Console.WriteLine("saurus exists"); 
+8
c #
source share
2 answers

Try the following:

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

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

+14
source share

Use Any :

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

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

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

but Any more portable (i.e. can be used with any enumerable, and not just List s.

+14
source share

All Articles