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;
Share:
19,476
pierre
Author by

pierre

Updated on June 05, 2022

Comments

  • pierre
    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 whose Property[3].Value does not StartWith 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
    pierre over 12 years
    This one worked for me first time and was a one-liner. Thank you.
  • sll
    sll over 12 years
    The 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 word ANY
  • sll
    sll over 12 years
    @pierre : nice to hear, I would suggest covering such logic by unit tests looking forward
  • Enigmativity
    Enigmativity over 12 years
    With All it won't ever return any results. It should be Any.
  • sll
    sll over 12 years
    looks like there is some confusion, we have to ask OP what is work for him
  • sll
    sll over 12 years
    From 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
    sll over 12 years
    @pierre: can you confirm that All() won't work and Any() gives you right results so I will update my answer
  • sll
    sll over 12 years
    I've found what I've missed, NOT should be before StartsWith() not before the (All),
  • Enigmativity
    Enigmativity over 12 years
    The 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.