Do we have a “Contains” method in IEnumerable

前端 未结 3 1406
挽巷
挽巷 2021-01-11 09:41

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 so

相关标签:
3条回答
  • 2021-01-11 10:25

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

    using System.Linq;
    

    and then:

    IEnumerable<string> foos = new[] { "foo", "bar", "baz" };
    bool IsThereABar = foos.Contains("bar");
    
    0 讨论(0)
  • 2021-01-11 10:42

    Do you really implement 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 Contains extension method.

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

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

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

    0 讨论(0)
  • 2021-01-11 10:44
    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

    0 讨论(0)
提交回复
热议问题