C# 的 LINQ 方法 DistinctBy
不能直接處理嵌套對象。但是,你可以通過使用 Select
和 Distinct
方法組合來實現處理嵌套對象的功能。以下是一個示例:
假設你有一個類 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
類的屬性(例如,Street
和 City
)獲取不重復的 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
方法創建一個新的匿名對象,其中包含 Name
、Street
和 City
屬性。然后,我們使用 Distinct
方法根據這些屬性獲取不重復的對象。最后,我們遍歷 distinctPeople
列表并輸出結果。