使用Linq查找重復


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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM