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?

Stavros_S
  • 2,145
  • 7
  • 31
  • 75
  • You could execute a LINQ query against `SomeIds` and then `foreach` against that filtered list. – David Tansey Mar 27 '15 at 20:24
  • Possible duplicate: http://stackoverflow.com/questions/12291953/how-to-check-if-a-enum-contain-a-number – Setsu Mar 27 '15 at 20:24
  • @Setsu that seems to be asking a different question. – Stavros_S Mar 27 '15 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. – Setsu Mar 27 '15 at 20:40

1 Answers1

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>())
AlexD
  • 32,156
  • 3
  • 71
  • 65