加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:37:14 所属栏目:百科 来源:网络整理
导读:我有一个通用的List,我必须在这个列表中找到一个特定的字符串.能否请您告诉我下面哪种方法最好? if (strlist.Contains("Test")){ // String found} 要么 string res = (from d in strlist where d == "Test" select d).SingleOrDefault();if (res == "Test"
我有一个通用的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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读