问题
Hi i have a class like this..
class man
{
public string name { get; set; }
public string houseid { get; set; }
}
and I have a list of man like this..
List<man> ppl = new List<man>();
I want to search if there are more than one person with the same houseid. If there are more than one man with same house id and if the number of people having same house id does not exceed limit 5 I want that house ids and the number of occurrences of that house id? Simply if there are houses with less than 5 members I want that house ids and the number of men under that house id? How to do that?
回答1:
You can use:
var houses = ppl.GroupBy(x => x.houseid) // 1
.Where(x => x.Count() < 5) // 2
.Select(x => new { HouseID = x.Key, Population = x.Count() }); // 3
- Group the peoples based on houseid
- Get the groups that contains less than five items
- Create anonymous type for each group that contains the id of the House and the population.
回答2:
Sounds like you need a GroupBy
var houses = ppl.GroupBy(x => x.houseid)
.Where(g => g.Count() < 5)
.Select(g => new { Id = g.Key, Count = g.Count());
foreach (var house in houses)
{
Console.WriteLine("House {0} has a population of {1}", house.Id, house.Count);
}
来源:https://stackoverflow.com/questions/23782492/how-to-search-for-matching-items-in-an-object-list