gpt4 book ai didi

c# - 如何使用linq通过主键组合三个对象列表

转载 作者:行者123 更新时间:2023-11-30 15:42:55 24 4
gpt4 key购买 nike

我正在尝试合并 3 个对象列表。我有一个人员列表、地址列表和地址关系列表。我想将这些列表组合成一个按 person.id 排序的新列表,将其用作 ListView 的数据源,然后能够访问 aspx 页面中的属性。

这可能吗?

最佳答案

大致

using System.Linq;

class Person
{
public int Id;
public string Name;
}

class Address
{
public int Id;
public string Street;
}

class PersonAddress
{
public int PersonId, AddressId;
}

public class Program
{
public static void Main(string[] args)
{
var personList = new []
{
new Person { Id = 1, Name = "Pete" },
new Person { Id = 2, Name = "Mary" },
new Person { Id = 3, Name = "Joe" }
};

var addressList = new []
{
new Address { Id = 100, Street = "Home Lane" },
new Address { Id = 101, Street = "Church Way" },
new Address { Id = 102, Street = "Sandy Blvd" }
};

var relations = new []
{
new PersonAddress { PersonId = 1, AddressId = 101 },
new PersonAddress { PersonId = 3, AddressId = 101 },

new PersonAddress { PersonId = 2, AddressId = 102 },
new PersonAddress { PersonId = 2, AddressId = 100 }
};

var joined =
from par in relations
join p in personList
on par.PersonId equals p.Id
join a in addressList
on par.AddressId equals a.Id
select new { Person = p, Address = a };

foreach (var record in joined)
System.Console.WriteLine("{0} lives on {1}",
record.Person.Name,
record.Address.Street);
}
}

输出:

Pete lives on Church Way
Mary lives on Sandy Blvd
Mary lives on Home Lane
Joe lives on Church Way

关于c# - 如何使用linq通过主键组合三个对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7160031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com