gpt4 book ai didi

c# - 在通用列表中搜索项目时,我应该使用 LINQ 还是 Contains?

转载 作者:行者123 更新时间:2023-11-30 14:19:05 24 4
gpt4 key购买 nike

我有一个通用的 List,我必须在这个列表中找到一个特定的字符串。您能否告诉我以下哪种方法最好?

if (strlist.Contains("Test"))
{
// String found
}

string res = (from d in strlist where d == "Test" select d).SingleOrDefault();

if (res == "Test")
{
//found
}

请考虑从数据库中填充的列表可能非常大。非常感谢您对此的看法。

最佳答案

如果你有List<string> (甚至 IEnumerable<string>)和 Contains 满足您的需求,然后使用 Contains。

如果您需要一些 Contains 不提供的额外处理,我建议您使用 Any():

if(strList.Any(s => s.StartsWith("Tes"))
{
// Found
}

关于c# - 在通用列表中搜索项目时,我应该使用 LINQ 还是 Contains?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3354671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com