Distinct部分用法

Linq 用来实现集合(List, DataTable等) 的二次操作十分简便,下面是用 Linq 对集合进行 Distinct 操作的几种方法。

1. 使用GroupBy:对需要Distinct的字段进行分组,取组内的第一条记录这样结果就是Distinct的数据了。

            var type = (from log in db.SYS_USEROPR
                        group log by log.VC_USROPRTYPE into a
                        select a.FirstOrDefault()
                        ).ToList();

2. 使用Distinct()扩展方法:需要实现IEqualityComparer接口。

        public class TypeCompare : IEqualityComparer
        {
            public bool Equals(SYS_USEROPR x, SYS_USEROPR y)
            {
                return (x.VC_USROPRTYPE == y.VC_USROPRTYPE);
            }

            public int GetHashCode(SYS_USEROPR obj)
            {
                return obj.VC_USROPRTYPE.GetHashCode();
            }
        }

使用

            var type = db.SYS_USEROPR.ToList().Distinct(new TypeCompare()).ToList();

3. 自定义扩展方法DistinctBy(this IEnumerable source, Func keySelector)

public static class MyEnumerableExtensions
{
    public static IEnumerable DistinctBy
        (this IEnumerable source, Func keySelector)
    {
        HashSet seenKeys = new HashSet();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element))) { yield return element; }
        }
    }
}

准备数据:

public class User
{
    public string A;
    public string B;
    public string C;
    public string D;

    public override string ToString()
    {
        return string.Format("{0},{1},{2},{3}", A, B, C, D);
    }

    public static List GetData()
    {
        return new List { 
            new User { A = "a1", B = "b1", C = "c1", D = "d1" },
            new User { A = "a1", B = "b1", C = "c1", D = "d1" },
            new User { A = "a2", B = "b1", C = "c1", D = "d1" },
            new User { A = "a1", B = "b2", C = "c1", D = "d1" },
            new User { A = "a1", B = "b1", C = "c1", D = "d1" },
            new User { A = "a1", B = "b1", C = "c2", D = "d1" },
            new User { A = "a1", B = "b1", C = "c1", D = "d2" },
        };
    }
}
var test = User.GetData().DistinctBy(x => new { x.A, x.B, x.C });

参考:http://blog.csdn.net/fangxinggood/article/details/6187043

转载于:https://www.cnblogs.com/w-y-f/archive/2012/04/10/2440986.html

你可能感兴趣的:(Distinct部分用法)