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<SYS_USEROPR>
        {
            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<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> seenKeys = new HashSet<TKey>();
        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<User> GetData()
    {
        return new List<User> { 
            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

posted on 2012-04-10 17:39  ※WYF※  阅读(2645)  评论(0编辑  收藏  举报