9

I have a list.

It's possible members (x123, y123, z123, a123, b123, c123).//123 is example This "mylist" may contain a member that starting with x, or may not. Also this is the same for y,z,a,b,c.

If contains a member starts with x:
//Formula Contains X

If Not Contains a member starts with x:
//Formula Not Contains X

//same as all of x,y,z,a,b,c. But unlike a foreach, I must place the formulas at checking time, not after.

How can I do that?

2
  • it would not be a problem,the important thing is job, i can use.
    – ithnegique
    Jun 4, 2013 at 18:23
  • Ok. I posted an answer for contains and not contains Jun 4, 2013 at 18:31

4 Answers 4

18

Checks if any items start with 'x' in your list:

bool result = mylist.Any(o => o.StartsWith("x"))

Checks if no items start with 'x' your list:

bool result = !mylist.Any(o => o.StartsWith("x"));
0
6

You can use .Any from Linq

bool result = mylist.Any(o => o.StartsWith("x"));

This will iterate on the list and tell you if there is at least one element that starts with "x"

1
  • In this solution where must I place myList?
    – ithnegique
    Jun 4, 2013 at 18:28
4
public void Process(List<string> list, string key)
{
    if (list.Any(i => i.StartsWith(key)))
    {
        //Formula Contains key
    }
    else
    {
        //Formula Not Contains key
    }
}

then you can call

List<string> list = new List<string> { "x123", "y123", "z123", "a123", "b123", "c123"};
Process(list, "x");
Process(list, "a");
1
List<string> formula = new List<string> { "x123", "y123" };
string variable = "x";
bool containsVariable = formula.Any(s => s.StartsWith(variable));
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.