【发布时间】:2021-01-28 16:43:37
【问题描述】:
我尝试通过 linq 获取孩子的孩子的唯一列表。我的意思是,我有clients 和bars 住在cities。酒吧可以拥有相同的客户。
我需要一个唯一的客户列表,所以我喜欢这样(代码小提琴here):
public class Program
{
class Client { public int Id { get; set; } }
class Bar
{
public int Id { get; set; }
public ICollection<Client> Clients;
}
class City
{
public int Id { get; set; }
public ICollection<Bar> Bars;
}
public static void Main()
{
var clients = new Client[]
{
new Client() { Id = 5 },
new Client() { Id = 9 }
};
Bar b1 = new Bar() { Id = 1, Clients = clients };
Bar b2 = new Bar() { Id = 2, Clients = clients };
City c1 = new City() { Id = 1, Bars = new Bar[] { b1, b2 } };
City c2 = new City() { Id = 2, Bars = new Bar[] { } };
List<City> cities = new List<City>() { c1, c2 };
var barClients = cities.Select(c => c.Bars.Select(b => b.Clients));
foreach (var c in barClients)
Console.WriteLine(c.Id);
}
}
但这不起作用(它说的是集合的集合)
【问题讨论】: