Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

c# - 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 )

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...