14

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.

5 Answers 5

18
var result =  myCollection.Where(c =>  
                           exceptions.All(e => 
                                       !c.Property[3].Value.StartsWith(e));
Sign up to request clarification or add additional context in comments.

9 Comments

This one worked for me first time and was a one-liner. Thank you.
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
@pierre : nice to hear, I would suggest covering such logic by unit tests looking forward
With All it won't ever return any results. It should be Any.
looks like there is some confusion, we have to ask OP what is work for him
|
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;

Comments

3

You could use IndexOfAny (and check result is index position zero) as that takes a collection.

Comments

0

You can select the collection of item you don't want then do a IEnumerable.Except().

I should look like this :

var result = from c in myCollection               
             where not c.Property[3].Value.StartWith(exceptions)               
             select c;  

var finalResult = myCollection.Except(myCollection.Select(i => i.StartWith(exception)));

Comments

0
var result = myCollection
              .where(
                 rs=>exceptions
                 .where(
                     rs1=>!rs.property[3].value.startsWith(rs1)
                  )
              )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.