使用的foreach LINQ扩展类型约束 [英] Type Constraint on foreach using LINQ extensions

查看:105
本文介绍了使用的foreach LINQ扩展类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个方法某处这里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
}

这篇关于使用的foreach LINQ扩展类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆