C # Linq, searching for duplicate matching items

we have the following setting: We have an array of objects with a string in it (xml-ish, but not normalized), and we have a list / array of strings with an identifier.

We need to find out if a row from this list with id is also pressed in one of the objects.

Here we have the setting we tried:

public class Wrapper
{
    public string MyProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Wrapper> wrappers = new List<Wrapper>() 
        {
            new Wrapper{ MyProperty = "<flkds,dlsklkdlsqkdkqslkdlqk><id>3</id><sqjldkjlfdskjlkfjsdklfj>"}, 
            new Wrapper{ MyProperty = "<flkds,dlsklkdlsqkdkqslkdlqk><id>2</id><sqjldkjlfdskjlkfjsdklfj>"}
        };
        string[] ids = { "<id>0</id>", "<id>1</id>", "<id>2</id>" };

        var props = wrappers.Select(w => w.MyProperty);
        var intersect = props.Intersect(ids, new MyEquilityTester());
        Debugger.Break();
    }
}

class MyEquilityTester: IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return x.Contains(y);
    }

     public int GetHashCode(string obj)
     {
         return obj.GetHashCode();
     }
 }

Edit:

What we expect is when we do .Any()on intersect, which says true, because wrappers have an object with support that contains <id>2</id>, intersectis null.

If we use the wrong method, tell me. It should work as fast as possible. Simple trueupon detection will do!

+5
source share
2 answers

IEqualitycomparer :

class MyEquilityTester: IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return x.Contains(y) || y.Contains(x);
    }

    public int GetHashCode(string obj)
    {
        return 0;
    }
}

<flkds,dlsklkdlsqkdkqslkdlqk><id>2</id><sqjldkjlfdskjlkfjsdklfj>

, GetHashCode 0 x.Contains(y) || y.Contains(x).


- Where Any

IEnumerable<String> intersect = props.Where(p => ids.Any (i => p.Contains(i)));

Where Any, , true false.

bool intersect = props.Any(p => ids.Any (i => p.Contains(i)));
+6
wrappers.Where(w=>ids.Any(i=>w.MyProperty.Contains(i)))
+1

All Articles