tags:

views:

376

answers:

4

I'm sure that I'm missing something simple here, but in Visual Studio 2008 on my current project only List.Contains(T) is present. Being able to use List.Contains(T, IEqualityComparer(T)) would save me a lot of grief. Any quick thoughts on this? Thanks.

*edit: using System.Linq is not available to me. Is is possible that my project is stuck in .net 2.0 or something along those lines? Anyway to check & fix?

+7  A: 

Make sure to reference System.Linq and include it (using System.Linq) in your namespaces.

The second call you are referring to is actually Enumerable.Contains in System.Linq.


Edit in response to comments:

You could make your own version:

public void ContainedInList(IEnumerable<T> list, T value, IEqualityComparer<T> comparer)
{
    foreach(T element in list)
    {
        if (comparer.Equals(element, value))
            return true;
    }
    return false;
}
Reed Copsey
Thank you for the reply. This option isn't available to me.
Alex
Sorry - that's where that method comes from. You could write your own contains method that takes a list and does that check, though - it'd be fairly easy. I'm assuming you're targeting .NET 2.0 then, instead of 3.5.
Reed Copsey
I edited to give you another option.
Reed Copsey
Thank you again for the help. I did some googling after I suspected that it was an issue with the version of .NET my project was using. It was pointing at .NET 2.0, after changing it to .NET 3.5 and adding using System.linq my problem was solved :)
Alex
Seems a little odd that you'd accept an answer that didn't actually address your issue when two other answers did.
Adam Robinson
+1  A: 

Ensure that your project's target framework (available in the project properties dialog) is set to .NET 3.5.

Adam Robinson
+1  A: 

Even if you're stuck in .NET 2.0 you can still define an extension method, provided you're working with the C# 3 compiler (that is, in Visual Studio 2008).

As per this post from Daniel Moth, you only need to define an "ExtensionAttribute" class somewhere in your code:

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute 
    {
    }
}

Now define your new "Contains" method:

public static class MyExtensions
{
    public static Contains<T>(this IEnumerable<T> list,
        T item, IEqualityComparer<T> comparer)
    {
        foreach (var i in list) if (comparer.Equals(item, i)) return true;
        return false;
    }
}
Matt Hamilton
+2  A: 

To check to see if your target framework is 2.0, go to Project>Properties, on the Application tab you will see "Target Framework"

Set it to .NET Framework 3.5.

If this is set, System.Linq should be available to you.

Jeff Hall