【问题标题】:Filter out value in foreach loop if it does not match any values in enum如果它与枚举中的任何值都不匹配,则过滤掉 foreach 循环中的值
【发布时间】:2015-03-27 20:18:39
【问题描述】:

如果 foreach 循环中的值与特定枚举中的任何值都不匹配,我该如何跳过它。例如:

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
}

过去我在类似的情况下使用LINQ过滤掉0,我可以在这里做类似的事情吗?

【问题讨论】:

  • 您可以针对SomeIds 执行LINQ 查询,然后针对该过滤列表执行foreach
  • @Setsu 似乎在问一个不同的问题。
  • @Stavros_S 不,它问的是嵌入在你的问题中的潜在问题。为了过滤掉不在枚举中的值,您必须首先能够判断枚举中是否存在特定值。一旦知道这一点,您的解决方案就可以归结为循环体中的一个简单 if 语句。

标签: c# .net


【解决方案1】:

试试

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

如果SomeIds 是整数列表,则添加Cast

foreach(var id in SomeIds.Where(x => Enum.IsDefined(typeof(IDs), x)).Cast<IDs>())

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 2019-06-04
    • 2018-09-15
    • 2023-02-09
    • 2015-03-17
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多