IEqualityComparer for Annoymous Type

前端 未结 2 1715
爱一瞬间的悲伤
爱一瞬间的悲伤 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 14:54

    This post may get what you want. Although for .NET 2.0 it also works for newer versions (see the bottom of this post for how to achieve this). In contrast to Jon Skeets solution we won´t use a factory-method like create. But this is only syntactic sugar I think.

    0 讨论(0)
  • 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<T> Create<T>(
            IEnumerable<T> example,
            Func<T, T, bool> equalityCheck,
            Func<T, int> hashCodeProvider)
        {
            return new EqualityComparerImpl<T>(equalityCheck, hashCodeProvider);
        }
    
        private sealed class EqualityComparerImpl<T> : IEqualityComparer<T>
        {
            // 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.

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