distinct不适用于我的查询c#linq

时间:2016-08-23 16:34:59

标签: c# linq distinct

我有这个查询,你可以在这里看到:

 public IQueryable<ViewReportMaterialRequestContractor> ShowReport(int MRCId)
        {
            var q = from m in _ctx.MaterialRequestContractorDetails
                    where m.MaterialRequestContractorId == MRCId

                    join mat in _ctx.MaterialDescriptions on m.MaterialDescriptionId equals mat.Id
                    join l in _ctx.Lines on m.LineId equals l.Id 
                    join joint in _ctx.Joints on m.LineId equals joint.LineId 


                    join sheet in _ctx.Sheets on joint.SheetId equals sheet.Id
                    join testjoint in _ctx.TestPackageJoints on joint.Id equals testjoint.Id

                    join testpack in _ctx.TestPackages on testjoint.TestPackageId equals testpack.Id
                    select new ViewReportMaterialRequestContractor()
                    {
                        Id = m.Id,
                        ItemCode = mat.ItemCode,
                        LineNumber = l.LineNumber,
                        Description = mat.Description,
                        Size1 = mat.Size1.ToString(),
                        Size2 = mat.Size2.ToString(),
                        DocumentNumber = l.DocumentNumber,

                    };
            return q;

        }

我可以在UI中调用我的函数,如您所见:

    List<ViewReportMaterialRequestContractor> lstMaterialRequestContractorDetails = _reportMaterialRequestContractorRepository.ShowReport(Id).ToList().Distinct().ToList();

我的记录重复4次,我有4条记录重复4次,所以我有16条记录。所以我必须使用distinct删除重复记录。

但结果又显示了16条记录。为什么?

1 个答案:

答案 0 :(得分:1)

.ShowReport(Id).ToList().Distinct().ToList() Distinct()被调用的.ToList()Enumerable.Distinct<TSource>(this IEnumerable<TSource> source)时,这将从第一个ViewReportMaterialRequestContractor创建一个内存中集合,然后使用相等规则进行区分在.NET中用于.Equals(object)类(默认情况下将按对象引用进行比较,如果未覆盖.GetHashCode().ShowReport(Id).Distinct().ToList(),则不是按值进行比较)

Distinct() Test-ModuleManifest 被调用的$string = "2010-11-24"; $date = new DateTime($string); echo date_format($date, 'd'); Queryable.Distinct<TSource>(this IQueryable<TSource> source)时,这会将distinct in转换为SQL查询调用,并使用SQL Server中的相等规则在服务器上执行(将按每个返回列的值进行比较)