C# 我们在 IEnumerable 中有“包含”方法吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13767277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:44:55  来源:igfitidea点击:

Do we have a "Contains" method in IEnumerable

c#

提问by Bohn

I have a class in my code that is already deriving from IEnumerable. I was wondering if there is a way that I can use a "Contains" method on its instnaces to look for a something in that list?

我的代码中有一个类已经从 IEnumerable 派生。我想知道是否有一种方法可以在其实例上使用“包含”方法来查找该列表中的某些内容?

采纳答案by Jon Skeet

Do you reallyimplement the non-generic IEnumerable, or the generic IEnumerable<T>? If you can possibly implement the generic one, your life will become a lot simpler - as then you can use LINQ to Objects, which does indeed have a Containsextension method.

真的实现了非泛型IEnumerable,还是泛型IEnumerable<T>?如果你可以实现通用的,你的生活就会变得简单得多——因为这样你就可以使用LINQ to Objects,它确实有一个Contains扩展方法。

Otherwise, you could potentially convert from the non-generic to generic using Castor OfType, e.g.

否则,您可能会使用Castor将非泛型转换为泛型OfType,例如

bool found = nonGeneric.Cast<TargetType>().Contains(targetItem);

It would be nicer if you just implemented the generic interface to start with though :)

如果您只是实现了通用接口,那就更好了:)

回答by Darin Dimitrov

No, there's no such method in the IEnumerable<T>interface. There's an extension methodthough that you could use.

不,IEnumerable<T>界面中没有这样的方法。有一个extension method虽然你可以使用。

using System.Linq;

and then:

进而:

IEnumerable<string> foos = new[] { "foo", "bar", "baz" };
bool IsThereABar = foos.Contains("bar");

回答by Smagin Alexey

public static bool Contains<T>(this IEnumerable source, T value)
    {
        foreach (var i in source)
        {
            if (Equals(i, value))
                return true;
        }
        return false;
    }

If you want, you can add custom comparer as parameter ti extension method Contains

如果需要,您可以添加自定义比较器作为参数 ti 扩展方法包含