Get individual items by combination from C # list

My object is 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 these objects in this class where the data is similar to

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

I want to filter this list to get output like this

  Rodney , 7845 , Auckland Rodney , 3445 , North Island 

(all possible combination of city and region, regardless of zip code). I wrote several such requests

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

But this gives me the result of the first element only as

  Rodney , 7845 , Auckland 

How can I solve this problem?

+5
source share
2 answers

You need to use GroupBy

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

This will give you groups by region and city, and then you can simply select the first item in each group.

+7
source

You can use DistinctBy to solve this problem as follows:

 var cities = regionsData.DistinctBy(x => (x.City, x.WfRegion)); 

Note that this uses the C # 7 tuple syntax. For older versions, you should use an anonymous type as follows:

 var cities = regionsData.DistinctBy(x => new {x.City, x.WfRegion}); 

Full console example:

 using System; using System.Collections.Generic; using MoreLinq; namespace ConsoleApp1 { public class Region { public string City { get; set; } public int PostCode { get; set; } public string WfRegion { get; set; } public override string ToString() { return $"City:{City}, PostCode:{PostCode}, WfRegion:{WfRegion}"; } } class Program { static void Main() { IEnumerable<Region> regions = new [] { new Region { City = "CityOne", PostCode = 1, WfRegion = "WfRegionOne"}, new Region { City = "CityOne", PostCode = 2, WfRegion = "WfRegionTwo"}, new Region { City = "CityTwo", PostCode = 3, WfRegion = "WfRegionOne"}, new Region { City = "CityOne", PostCode = 4, WfRegion = "WfRegionOne"}, new Region { City = "CityOne", PostCode = 5, WfRegion = "WfRegionThree"}, new Region { City = "CityTwo", PostCode = 6, WfRegion = "WfRegionOne"}, new Region { City = "CityTwo", PostCode = 7, WfRegion = "WfRegionThree"} }; var result = regions.DistinctBy(x => (x.City, x.WfRegion)); Console.WriteLine(string.Join("\n", result)); } } } 
0
source

Source: https://habr.com/ru/post/1267351/


All Articles