I am looking to find all the dealers in the database that have a duplicate phone number. I then want to list them in a report with all the dealers information. I am having trouble getting my select statement to populate the dealer record attributes.
Such as dealer name address and so fourth. I am thinking it is because of the group by that is limiting it.
var dealers = _db.Dealers
.Where(x => x.Active)
.GroupBy(x => x.Phone)
.Select(x => new { Dealer = x.Key, Phone = x.Count()})
.Where(x => x.Phone > 1);
Edit: The desired output would be list of each dealer. I want the dealers with the same phone number to appear next to each other. I don't want any records that are not duplicates based on phone number.
Just add the first item in the group to the last Select:
var dealers = _db.Dealers
.Where(x => x.Active)
.GroupBy(x => x.Phone)
.Select(x => new { Dealer = x.Key, Phone = x.Count(), FirstItem = x.First()})
.Where(x => x.Phone > 1);
the result will then have a FirstItem
property
Or if you want all the items in a flat list you can apply the Where
directly to the grouping:
var dealers = _db.Dealers
.Where(x => x.Active)
.GroupBy(x => x.Phone)
.Where(g => g.Count() > 1);
.SelectMany(g => g) // flat list of Dealers
You're not saying exactly what the expected output and the actual output is, so I don't know what you mean by 'having trouble'. But I spotted one potentially confusing thing:
You're grouping by the Phone ( .GroupBy(x => x.Phone)
).
So when you do new { Dealer = x.Key, ...
the x.Key
will refer to the phone number of this group.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.