2017-05-01 36 views
5

我的對象喜歡這樣獲得通過組合不同的項目

public class Region 
{ 
    public Region(); 

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

我在哪裏的數據是這樣的

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

這個對象在這個類的列表,我要篩選此列表,以便我能得到這樣的

Rodney , 7845 , Auckland 
    Rodney , 3445 , North Island 

輸出(城市和區域的所有可能的組合,而不管郵編)。 我已經寫了一些這樣的查詢

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

但是,這是給我的第一個項目的結果只有這樣

 Rodney , 7845 , Auckland 

我怎樣才能解決這個問題呢?

回答

7

您需要使用GroupBy

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

這將使你在地區和城市分組,然後你可以選擇每個組中的第一項。

0

您可以使用DistinctBy來解決這個問題如下:

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

注意,這是用C#7元組的語法。

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

完全控制檯例如:

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)); 
     } 
    } 
} 
對於舊版本,您必須按如下方式使用匿名類型