LinQ WHERE string.contains或string.IndexOf? [英] LinQ WHERE string.Contains or string.IndexOf?
问题描述
我需要写一些与以下内容相同的结果
I need to write something that would give the same result as:
var result = collection.Where( o => o.Name.IndexOf( "some_string2" ) != -1 || o.Name.IndexOf( "some_string_2" ) != -1 || o.Name.IndexOf( "some_string3" ) != -1 )
要检查的字符串的数量和值(some_string_1、2和3)是未知的(来自DB),因此更通用...
Where the amount and values of the strings to check for (some_string_1, 2 and 3) are unknown (coming from DB), so something more generic...
我尝试了以下操作,但失败了...
I tried the following, but failed...
var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();
var result = collection.Where( o => stringsToCheck.Contains( o.ToLower() ) );
换句话说,我需要从名称中包含某些特定字符串的集合中检索所有对象.
In other words, I need to retrieve all the objects from a collection which names contain some specific strings.
推荐答案
var result = collection.Where(item => stringsToCheck.Any(stringToCheck =>
item.Name.Contains(stringToCheck)));
用英语读这是:给我集合中的所有项目,其中要检查的所有字符串中的所有字符串之一都是集合中字符串的子字符串.
Read in English this is: give me all of the items in the collection where, of all of the strings to check one of them is a substring of the string in the collection.
这篇关于LinQ WHERE string.contains或string.IndexOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!