简体   繁体   English

按属性分组的列表以及出现多次的列表

[英]group list by property and where it appears more than once

I have a list of objects of type student. 我有一个学生类型的对象列表。

 public class Student
 {
    string FirstName
    string Surname
    int Age
 }

I want my to group students with the same surname together and return a list of those surnames where a surname appears more than once. 我希望将具有相同姓氏的学生归为一组,并返回一个姓氏出现多次的那些姓氏列表。 Eg, 例如,

 Surname
 Bloggs
 Joe
 Bloggs
 Smith
 Tom
 Smith

My new list would just have 我的新清单只有

 Bloggs
 Smith

Here is the code I am currently using which works however is there a way in my linq statement to specify to return surnames that appear more than once? 这是我当前正在使用的代码,但是我的linq语句中是否有一种方法可以指定返回出现多次的姓氏?

var res = hldList.GroupBy(hld => hld.MyID).ToList();

foreach(var id in res)
{
    var total = id.Count();
    if(total >1)
    // do something
}

Group list on SurName and filter those whose count is greater than 1 : SurName上分组列表,并过滤计数大于1的那些:

var duplicateSurNames = ldList.GroupBy(hld => hld.Surname)
                              .Where(g=>g.Count() > 1)
                              .Select(x=>x.Key).ToList();
hldList
  .GroupBy(hld => hld.SurName)
  .Select(hld => new { key = hld.Key, count = hld.Count() })
  .Where(hld => hld.count > 1)
  .ToList();

if you don't want the counts, you can add another projection at the end: 如果您不希望计数,则可以在末尾添加另一个投影:

  .Where(hld => hld.count > 1)
  .Select(hld => hld.key)
  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM