我有两个班级:
class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
class Phone
{
public int PersonId { get; set; }
public string Number { get; set; }
}
两个系列:
List<Person> Persons;
List<Phone> Phones;
我想使用linq加入他们并获取Result对象的结果列表:
class Result
{
public string Name { get; set; }
public List<string> Numbers { get; set; }
}
如何在linq中实现这个?
答案 0 :(得分:4)
var resultList =
from person in Persons
select new Result
{
Name = person.Name,
Numbers =
(
from phone in Phones
where phone.PersonId == person.PersonId
select phone.Number
).ToList()
}
答案 1 :(得分:1)
您可以使用Linq的连接功能
var joinedList = from c in Persons
join p in Phones p on p.PersonId equals c.PersonId
select new {Persons = c, Phones = p};
更新:
似乎必须将其作为结果返回。我们走了。
var results = Persons.Select(c => new Result
{
Name = c.Name,
Numbers = Phones.Where(p=>p.PersonId == c.PersonId)
.Select(n=>n.Number).ToList()
});
答案 2 :(得分:1)
假设所有电话号码都指向一个现有的人,这将起作用:
var results = Phones.GroupBy(p => p.PersonId)
.Select(g => new Result()
{
Name = Persons.Single(x => x.PersonId == g.Key).Name,
Numbers = g.Select(x => x.Number).ToList()
});
答案 3 :(得分:1)
非常类似迈克......
var resultList = from person in persons
select new Result
{
Name = person.Name,
Numbers = phones
.Where(x => x.PersonId == person.PersonId)
.Select(x => x.Number)
.ToList()
};
答案 4 :(得分:1)
List<Person> people = new List<Person>(); /*Populate the list however you wish*/
List<Phone> phones = new List<Phone>(); /*Populate the list however you wish*/
List<Result> results = people
.Select(singlePerson => new Result
{
Name = singlePerson.Name,
Numbers = phones
.Where(singlePhone => singlePhone.PersonId.Equals(singlePerson.PersonId))
.Select(singlePhone => singlePhone.Number)
.ToList()
})
.ToList();
答案 5 :(得分:1)
好吧,我不会只是通过向人们添加电话项目来加入这两个系列。根据你想要实现的目标,我会使用一个接口来指定这两个类有一些共同点。
但其他解决方案也可以运行,根据您的问题,它可能不是正确的解决方案。