Using Distinct with LINQ and Objects

后端 未结 5 1393
余生分开走
余生分开走 2021-01-03 23:20

Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class

5条回答
  •  被撕碎了的回忆
    2021-01-03 23:30

    You're not doing it wrong, it is just the bad implementation of .Distinct() in the .NET Framework.

    One way to fix it is already shown in the other answers, but there is also a shorter solution available, which has the advantage that you can use it as an extension method easily everywhere without having to tweak the object's hash values.

    Take a look at this:


    **Usage:**
    var myQuery=(from x in Customers select x).MyDistinct(d => d.CustomerID);
    

    Note: This example uses a database query, but it does also work with an enumerable object list.


    Declaration of MyDistinct:

    public static class Extensions
    {
        public static IEnumerable MyDistinct(this IEnumerable query, 
                                                        Func f)
        {
            return query.GroupBy(f).Select(x=>x.First());
        }
    }
    

    Or if you want it shorter, this is the same as above, but as "one-liner":

    public static IEnumerable MyDistinct(this IEnumerable query, Func f) 
                                 => query.GroupBy(f).Select(x => x.First());
    

    And it works for everything, objects as well as entities. If required, you can create a second overloaded extension method for IQueryable by just replacing the return type and first parameter type in the example I've given above.

提交回复
热议问题