Mauritz Swanepoel Mauritz Swanepoel - 3 months ago 8
C# Question

Linq distinct rows based on field within the result

I am trying to filter my results below to only show distinct rows based on the MacAddress field being returned within the select. This works when just returning single values but not on the objects. Any ideas?

// Get all records which have not been imported yet?
var query = (from s in db.Stagings
join t in db.Printers on s.MacAddress equals t.MacAddress into tj
from t in tj.DefaultIfEmpty()
where t == null
select new { s.MacAddress,s.PrinterName,s.HostName,s.IPAddress,s.ReportDate}).Distinct();


Is it possible to further filter without doing a loop?

Answer

Will this work?

var query = (from s in db.Stagings
                join t in db.Printers on s.MacAddress equals t.MacAddress into tj
                from t in tj.DefaultIfEmpty()
                where t == null
                select new { s.MacAddress,
                            s.PrinterName,
                            s.HostName,
                            s.IPAddress,
                            s.ReportDate
                        }
                ).GroupBy(s => s.MacAddress)
                .Select(s => s.First());