Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get from a object list only one by object value

I have a complete list of objects "Person".

I need a short list that includes only the first person from each team, so some sort of grouping and the first item in each case

How can I transfer the complete list into the short list with the first item per group and teamNumber?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<Person> list = new List<Person>()
{
    new Person(){TeamNumber = 1, Name = "Peter"},
    new Person(){TeamNumber = 1, Name = "Klaus"},
    new Person(){TeamNumber = 1, Name = "Maria"},
    new Person(){TeamNumber = 1, Name = "Gerda"},
    new Person(){TeamNumber = 2, Name = "Ralf"},
    new Person(){TeamNumber = 2, Name = "Oskar"},
    new Person(){TeamNumber = 2, Name = "Anna"},
    new Person(){TeamNumber = 3, Name = "Hannah"},
    new Person(){TeamNumber = 3, Name = "Susi"},
    new Person(){TeamNumber = 4, Name = "Ida"}
};

I like to get a short list like:
(allways the first person per teamNumber)

  • TeamNumber = 1, Name = "Peter"
  • TeamNumber = 2, Name = "Ralf"
  • TeamNumber = 3, Name = "Hannah"
  • TeamNumber = 4, Name = "Ida"

class Person:

public class Person
{
    public int TeamNumber { get; set; }
    public string Name { get; set; }
}

>Solution :

 var result= list.GroupBy(t => t.TeamNumber).Select(p => p.First()).ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading