Compare value to array of strings using StartsWith
19,476
Solution 1
var result = myCollection.Where(c =>
exceptions.All(e =>
!c.Property[3].Value.StartsWith(e));
Solution 2
You could use IndexOfAny (and check result is index position zero) as that takes a collection.
Solution 3
Try this:
string[] exceptions = new string[] { "one", "two", "one_1", "three" };
var result = from c in myCollection
where !exceptions.Any(exception =>
c.Property[3].Value.StartsWith(exception))
select c;
Author by
pierre
Updated on June 05, 2022Comments
-
pierre almost 2 years
I have an array:
string[] exceptions = new string[] { "one", two", "one_1", "three" };
.. I want to be able to say:
var result = from c in myCollection where not c.Property[3].Value.StartWith(exceptions) select c;
So I want
myCollection
to be filtered to only show those records whoseProperty[3].Value
does notStartWith
a value in the exceptions array. I know StartsWith doesn't take a collection so I'm unsure if this is possible via LINQ or not.Is this possible in LINQ?! Or am I trying to shoehorn my problem into a LINQ solution?
EDIT: I should say, Contains is not an option since I only want to exclude elements whose property startswith the exception string.
-
pierre over 12 yearsThis one worked for me first time and was a one-liner. Thank you.
-
sll over 12 yearsThe query returns collections with property does not start with ANY exception string,
!Any()
return true even a property does not start single exception but we need to ensure this for all exceptions, I believe there is some confusion with wordANY
-
sll over 12 years@pierre : nice to hear, I would suggest covering such logic by unit tests looking forward
-
Enigmativity over 12 yearsWith
All
it won't ever return any results. It should beAny
. -
sll over 12 yearslooks like there is some confusion, we have to ask OP what is work for him
-
sll over 12 yearsFrom my point of view you guys right so it should be
Any()
, I will update my answer when @pierre confirm this since answer already acepted -
sll over 12 years@pierre: can you confirm that
All()
won't work andAny()
gives you right results so I will update my answer -
sll over 12 yearsI've found what I've missed, NOT should be before
StartsWith()
not before the(All)
, -
Enigmativity over 12 yearsThe logic of "All Not Starts With" is the same as "Not Any Starts With". Quite different from "Not All Starts With". Well done on fixing the answer.