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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值