使用的foreach LINQ扩展类型约束类型、foreach、LINQ

由网友(稚气未脱)分享简介:我看到一个方法某处这里SO限制的项目从一个foreach循环返回到某种类型的,用的,如果我没记错的话,上了IEnumerable LINQ扩展和LAMDA的类型检查。我无法再次找到它,任何人都可以表明这是如何实现的呢?I have seen a method somewhere here on SO to restr...

我看到一个方法某处这里SO限制的项目从一个foreach循环返回到某种类型的,用的,如果我没记错的话,上了IEnumerable LINQ扩展和LAMDA的类型检查。我无法再次找到它,任何人都可以表明这是如何实现的呢?

I have seen a method somewhere here on SO to restrict items returned from a foreach loop to a certain type, using, if I remember correctly, LINQ extensions on IEnumerable and a lamda for the type check. I can't find it again, can anyone suggest how this was achieved?

推荐答案

您可以通过调用到Where扩展方法做到这一点,如下所示:

You could do this with a call to the Where extension method, as follows:

foreach(var x in theCollection.Where(i => i.GetType() == typeof(DesiredType))
{
     // Do something to x
}

但是,这是非常有用,它是建立在.NET框架中,而这正是克里斯上述指出。 IEnumerable的有一个叫OfType扩展方法,证明这里 。

But this is so useful that it is built into the .NET framework, and that is what Chris is pointing out above. IEnumerable has an extension method called OfType, documented here.

要使用它,你会做这样的事情:

To use it, you'd do something like this:

foreach(var x in theCollection.OfType<int>())
{
     // Do something to x
}
阅读全文

相关推荐

最新文章