簡體   English   中英

從列表C#中獲取組合的不同項

[英]Get distinct items by combination from list C#

我的對象就像這樣

    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

我該如何解決這個問題?

您需要使用GroupBy

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

這將為您提供區域和城市的分組,然后您可以選擇每個組中的第一個項目。

您可以使用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));
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM