I have two classes:
class Person
{
public int PersonId { get; set; }
public str开发者_Go百科ing Name { get; set; }
}
class Phone
{
public int PersonId { get; set; }
public string Number { get; set; }
}
And two collections:
List<Person> Persons;
List<Phone> Phones;
I would like to join them using linq and get as a result list of Result objects:
class Result
{
public string Name { get; set; }
public List<string> Numbers { get; set; }
}
How to implement this in linq?
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()
}
Assuming all phone numbers point to a single existing person this would work:
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()
});
Pretty similar to Mike...
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()
};
Pure Method Syntax:
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();
You can use the join function of Linq
var joinedList = from c in Persons
join p in Phones p on p.PersonId equals c.PersonId
select new {Persons = c, Phones = p};
Update :
Seems like it must be returned as Result. Here we go.
var results = Persons.Select(c => new Result
{
Name = c.Name,
Numbers = Phones.Where(p=>p.PersonId == c.PersonId)
.Select(n=>n.Number).ToList()
});
Well I wouldn't just join the 2 collections by adding phone items to persons. Depending on what you're trying to achieve I would use an interface to specify the 2 classes have something in common.
But the other solutions work as well it just might not be the right solution depending on your problem.
精彩评论