IEqualityComparer for Annoymous Type

前端 未结 2 1719
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-09 14:35

Firstly I have seen IEqualityComparer for anonymous type and the answers there do not answer my question, for the obvious reason that I need an IEqualityComparer no

2条回答
  •  星月不相逢
    2021-02-09 15:12

    Is there a way I can create my an IEquailityComparer for my anonymous types?

    Sure. You just need to use type inference. For example, you could have something like:

    public static class InferredEqualityComparer
    {
        public static IEqualityComparer Create(
            IEnumerable example,
            Func equalityCheck,
            Func hashCodeProvider)
        {
            return new EqualityComparerImpl(equalityCheck, hashCodeProvider);
        }
    
        private sealed class EqualityComparerImpl : IEqualityComparer
        {
            // Implement in the obvious way, remembering the delegates and
            // calling them appropriately.
        }
    }
    

    Then:

    var glext = m_dtGLExt.AsEnumerable();
    var query = from c in glext
                orderby ...
                select new { ... };
    var comparer = InferredEqualityComparer.Create(query,
        (x, y) => { ... },
        o => { ... }
    );
    var distinct = query.Distinct(comparer);
    

    Basically the first parameter to the method is just used for type inference, so that the compiler can work out what type to use for the lambda expression parameters.

    You could create the comparer ahead of time by creating a sample of the anonymous type:

    var sample = new[] { new { ... } };
    var comparer = InferredExqualityComparer.Create(sample, ...);
    var distinct = (... query here ... ).Distinct(comparer);
    

    but then any time you change the query you've got to change the sample too.

提交回复
热议问题