using System;
using System.Collections.Generic;
using System.Linq;
//人员实体
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
//创建人员列表
List<Person> persons = new List<Person>()
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "John", Age = 35 },
new Person { Name = "Jake", Age = 28 }
};
//将名字相同的去重,相同名称的默认取第一个
List<Person> distinctPersons = persons.GroupBy(p => p.Name)
.Select(g =>g.First())
.ToList();
foreach (Person person in distinctPersons)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
去重后输出
Name: John, Age: 25
Name: Jane, Age: 30
Name: Jake, Age: 28