• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#中两个ListTModel中根据指定条件--判断并获取不同数据的数据集合 ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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

方式一:

 public class Test
    {
        public int age { get; set; }
        public string name { get; set; }
        public int score { get; set; }
    }
            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数据参考方式一

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#如何取消BackgroundWorker异步操作发布时间:2022-07-10
下一篇:
[C#/.NET]howtoimplementwebapplicationlocalizationin.net4.0发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap