N. Kaufman
N. Kaufman

Reputation: 91

LINQ filter string with value string

I have a string str = "abc,def,ghi". The length of string will vary. There could be one or more values separated by comma.

I have an object that has a property Code that is string and can contain values such as - "abc, stu, xyz"

I'm trying to filter objects from a collection that will return only those that contain a string in str

So, if object.Code = "abc, stu, xyz" and string str = "abc,def,ghi" then return the object.

objects.Where( x => x.Code.Split(',').Any(s => (???)) );

where ??? is where my string str values will come in.

Thanks,

Upvotes: 0

Views: 535

Answers (2)

NetMage
NetMage

Reputation: 26917

Conversion of the str to a HashSet will improve the testing speed and simplify the query, but perhaps is overkill if your objects only have a few entries. I assume the Code property does not have spaces after each comma.

var strHash = str.Split(',').ToHashSet();
var ans = objects.Where(o => o.Code.Split(',', StringSplitOptions.RemoveEmptyEntries).Any(c1 => strHash.Contains(c1)));

Upvotes: 1

Pavel Shastov
Pavel Shastov

Reputation: 3007

var result = objects.Where(x => x.Code.Split(',').Any(s => (str.Split(',').Any(f => f.Equals(s)))));

Upvotes: 1

Related Questions