how to search for matching items in an object list?

二次信任 提交于 2019-12-25 00:36:14

问题


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
  1. Group the peoples based on houseid
  2. Get the groups that contains less than five items
  3. 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

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