Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get distinct items by combination from list C#

Tags:

c#

asp.net

linq

My object like like this

    public class Region
{
    public Region();

    public string City { get; set; }
    public int PostCode { get; set; }
    public string WfRegion { get; set; }
}

I have a list of this objects in this class Where data is like this

Rodney , 7845 , Auckland
Rodney , 3435 , Auckland
Rodney , 4566 , Auckland
Rodney , 3445 , North Island

I want to filter this list so that I can get an output like this

    Rodney , 7845 , Auckland
    Rodney , 3445 , North Island

(all the possible combination of city and region regardless of postcode). I have wrote some query like this

      var cities = regionsData.DistinctBy(p => 
p.WfRegion).DistinctBy(p=>p.PostCode).DistinctBy(p => p.City).ToList();

But this is giving me a result of first item only like this

        Rodney , 7845 , Auckland

How can I solve this issue?

like image 844
None Avatar asked May 01 '17 11:05

None


1 Answers

You need to use GroupBy

var result = regionsData.GroupBy(p => new {p.WfRegion, p.City})
    .Select(g => g.First())
    .ToList();

That will give you groupings by the region and city and then you can just select the first item in each group.

like image 132
juharr Avatar answered Oct 23 '22 01:10

juharr