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

linq Distinct 去掉重复问题
var query = (from j in db.Job
  join c in db.Company on j.UserId equals c.UserId
  into cj
  from c in cj.DefaultIfEmpty()
  select new
  {
  UserId = c.UserId,
  CompanyName = c.CompanyName,
  Jobs = c.Jobs
  }).Distinct().AsEnumerable().Select(b => new Company() { UserId = b.UserId, CompanyName = b.CompanyName, Jobs = b.Jobs.ToList() });

提示:无法将“Distinct”操作应用于所指定参数的集合 ResultType。
参数名: argument

------解决方案--------------------
探讨
没有 Jobs = c.Jobs 是可以的

------解决方案--------------------
C# code

public class DataRowComparer : IEqualityComparer<Company> 
    {  
        public bool Equals(Company  t1, Company  t2)  
        {  
            return (t1.UserId == t2.UserId 
                  && t1.CompanyName == t2.CompanyName
                 && t1.Jobs==t2.Jobs);  
        }  
        public int GetHashCode(Company  t)  
        {  
            return t.ToString().GetHashCode();  
        }  
    }  

var query = (from j in db.Job
  join c in db.Company on j.UserId equals c.UserId
  into cj
  from c in cj.DefaultIfEmpty()
  select new Company 
   {
    UserId = b.UserId, 
    CompanyName = b.CompanyName, 
    Jobs = b.Jobs.ToList() 
   }).Distinct(new DataRowComparer());