如何在List< string>中使用Exist在C#中 [英] how to use Exist in List<string> in C#
本文介绍了如何在List< string>中使用Exist在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须查找列表中是否存在字符串,以避免重复插入:这是Microsoft网站上的示例:
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");
}
}
是否可以用lambda表达式替换 EndsWithSaurus
函数?谢谢大家的投入!!这是一个工作代码:
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");
推荐答案
尝试一下:
if (dinosaurs.Exists(e => e.EndsWith("saurus")))
Console.WriteLine("saurus exists");
Any()
的答案也很好.区别只是 Exists()
方法本身来自 List< T>
本身,而 Any()
只是Linq扩展的重要功能之一方法(并且需要使用System.Linq
)
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
)
这篇关于如何在List< string>中使用Exist在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文