c#

c# distinctby能处理嵌套对象吗

小樊
81
2024-11-28 17:41:14
栏目: 编程语言

C# 的 LINQ 方法 DistinctBy 不能直接处理嵌套对象。但是,你可以通过使用 SelectDistinct 方法组合来实现处理嵌套对象的功能。以下是一个示例:

假设你有一个类 Person,其中包含一个嵌套的 Address 类:

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

现在,假设你有一个 List<Person>,你想要根据 Address 类的属性(例如,StreetCity)获取不重复的 Person 对象。你可以这样做:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Address = new Address { Street = "1st", City = "New York" } },
            new Person { Name = "Bob", Address = new Address { Street = "2nd", City = "New York" } },
            new Person { Name = "Charlie", Address = new Address { Street = "1st", City = "Los Angeles" } },
            new Person { Name = "David", Address = new Address { Street = "3rd", City = "New York" } }
        };

        var distinctPeople = people
            .Select(p => new
            {
                p.Name,
                p.Address.Street,
                p.Address.City
            })
            .Distinct();

        foreach (var person in distinctPeople)
        {
            Console.WriteLine($"Name: {person.Name}, Street: {person.Street}, City: {person.City}");
        }
    }
}

在这个示例中,我们首先使用 Select 方法创建一个新的匿名对象,其中包含 NameStreetCity 属性。然后,我们使用 Distinct 方法根据这些属性获取不重复的对象。最后,我们遍历 distinctPeople 列表并输出结果。

0
看了该问题的人还看了