1 namespace RemoveTheSame
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 List<User> list = new List<User>()
8 {
9 new User{Id=1,Name="user1",Pwd="123"},
10 new User{Id=2,Name="user1",Pwd="123"},
11 new User{Id=3,Name="user2",Pwd="123"}
12 };
13 GetTheSame(list, out string tkey);
14 Console.WriteLine($"The Same is {tkey}");
15 Console.ReadKey();
16 }
17 public static void GetTheSame(List<User> listOld, out string tkey/*,out User user*/)
18 {
19 tkey = null;
20 var result = from x in listOld
21 group x by x.Name into g
22 where g.Count() > 1
23 select g;
24 foreach (var item in result)
25 {
26 tkey = item.Key;
27 }
28 }
29 }
30 public class User
31 {
32 public string Name { get; set; }
33 public int Id { get; set; }
34 public string Pwd { get; set; }
35
36 }
37 }
其实就是一行代码解决的问题~
list.GroupBy(x => x.Name).Where(x => x.Count() > 1).ToList().ForEach(x => Console.WriteLine(x.Key));