欢迎莅临 SUN WU GANG 的园子!!!

世上无难事,只畏有心人。有心之人,即立志之坚午也,志坚则不畏事之不成。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  470 随笔 :: 0 文章 :: 22 评论 :: 30万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

C#中两个List<TModel>中根据指定条件--判断并获取不同数据的数据集合

原始需求:已经插入的数据不再重复插入(所有数据中排除已有数据,不存在数据以新对象形式存储在对象三种)

方式一:

1
2
3
4
5
6
public class Test
   {
       public int age { get; set; }
       public string name { get; set; }
       public int score { get; set; }
   }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
List<Test> list1 = new List<Test>();
list1.Add(new Test { score = 10, name = "001" });
list1.Add(new Test { score = 20, name = "002" });
list1.Add(new Test { score = 30, name = "003" });
list1.Add(new Test { score = 40, name = "004" });
list1.Add(new Test { score = 50, name = "005" });
list1.Add(new Test { score = 60, name = "005" });
 
List<Test> list2 = new List<Test>();
list2.Add(new Test { score = 10, name = "001" });
list2.Add(new Test { score = 20, name = "002" });
list2.Add(new Test { score = 30, name = "003" });
list2.Add(new Test { score = 40, name = "004" });
 
//list3 return 2
List<Test> list3 = list1.Where(x => !list2.Any(x2 => x.score == x2.score)).ToList();
//list4 return 2
List<Test> list4 = list1.Where(x => list2.All(x2 => x.score != x2.score)).ToList();
 
MessageBox.Show("list3==" + list3.Count+"\r\nlist4==" + list4.Count);    

方式二:list1、list2数据参考方式一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DifferentModel : IEqualityComparer<Test>
    {
        public bool Equals(Test x, Test y)
        {
            return x.score == y.score;
        }
 
        public int GetHashCode(Test obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
 
List<Test> different = list1.Except(list2, new DifferentModel()).ToList();//差集
 
MessageBox.Show("different=="+different.Count);

方式三:仅供参考,根据实际情况注意Contains关键字 注意使用——不建议使用

//return 2

List<Test> temp = list1.Where(p => !list2.Select(b => b.score).Contains(p.score)).ToList();
MessageBox.Show("temp=="+temp.Count);

 

posted on   sunwugang  阅读(3197)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示