How to combine three lists of objects by primary key using linq

扶醉桌前 提交于 2019-12-23 17:52:11

问题


I'm trying to combine 3 lists of objects. I have a person list, address list and an addressRelation list. I want to combine these lists into a new list ordered by person.id, use it as a datasource for a listview, and then be able to access the properties in the aspx page.

Is this possible?


回答1:


Roughly

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);
    }
}

Outputs:

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


来源:https://stackoverflow.com/questions/7160031/how-to-combine-three-lists-of-objects-by-primary-key-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!