日期:2014-05-20  浏览次数:20869 次

LINQ 去除重复的数据问题
各位大家好。
 var d1 = from p in tr.考试记录表
                     from pp in tr.考题分类表
                     where p.考题分类 == pp.id
                     where p.考试分数<100
                     where p.用户id == Common.Get_UserID
                     orderby p.id descending
                     select new { pp.考题分类名称, p.考试分数, p.id,p.答题个数,p.考题分类 };

问一个问题啊。考题分类有重复的。我想把重复的数据去掉,用.Distinct  但是不会写啊。
求解答啊。

var userlist=(from user in dc.Users
                  where user.name.contains(key)
                  select user).Distinct();

这是查询单项,但是我查询出来很多项啊。
------最佳解决方案--------------------
给你个扩展方法

        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; }
            }
        }


调用:比如根据考题分类与答题个数两项去重

         ar d1 = (from p in tr.考试记录表
         from pp in tr.考题分类表
         where p.考题分类 == pp.id
         where p.考试分数<100
         where p.用户id == Common.Get_UserID
         orderby p.id descending
         select new { pp.考题分类名称, p.考试分数, p.id,p.答题个数,p.考题分类 }).DistinctBy(p=>
         new { p.考题分类,p. 答题个数});

------其他解决方案--------------------
var resultCom = (fmsDb.Company_Investment.Where(c=>c.CompanyID==companyID).Select(c=>c.WebSite)).Distinct();
你可以这样试试看    select里面写你要查询的字段