Home > Software engineering >  How to get from a object list only one by object value
How to get from a object list only one by object value

Time:12-21

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?

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; }
}

CodePudding user response:

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

CodePudding user response:

I would go with this:

First you GroupBy TeamNumber in order to (group them, so you only get one. Then you take the First record (Person) and selects that for that TeamNumber. Then you do it for the whole list, and returns it as a new List.

var shortList =  list.GroupBy(t => t.TeamNumber).Select(e => e.FirstOrDefault()).ToList();

And then i would recommend you to read up on linq

  • Related