0

How can I skip a value in a foreach loop if it does not match any of the values in an specific enum. Ex:

public enum IDs
{
    SomeIdOne = 1001,
    SomeIdTwo = 1002,
    SomeIdThree = 1003
}

// one of the list items(7777) does not match what's in the IDs enum
var SomeIds = new List<IDs>() { 1002,7777,1001 };

// skip that item when looping through the list.
foreach (IDs id in SomeIds)
{
    // do things with id
}

In the past I have used LINQ to filter out 0 in a similar situation, can I do something like that here?

4
  • You could execute a LINQ query against SomeIds and then foreach against that filtered list. Commented Mar 27, 2015 at 20:24
  • Possible duplicate: stackoverflow.com/questions/12291953/… Commented Mar 27, 2015 at 20:24
  • @Setsu that seems to be asking a different question. Commented Mar 27, 2015 at 20:29
  • 1
    @Stavros_S No, it's asking the underlying question imbedded in yours. In order to filter out values not in the enum you must first be able to tell whether a particular value exists in the enum. Once you know that, your solution boils down to a simple if statement in the loop body. Commented Mar 27, 2015 at 20:40

1 Answer 1

2

Try

foreach(var id in SomeIds.Where(x => Enum.IsDefined(typeof(IDs), x)))
{
    //....
}

If SomeIds is a list of integers, add Cast:

foreach(var id in SomeIds.Where(x => Enum.IsDefined(typeof(IDs), x)).Cast<IDs>())
Sign up to request clarification or add additional context in comments.

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.