C#中两个List<TModel>中根据指定条件获取不同对象

博客园地址:https://www.cnblogs.com/YYkun/p/11639802.html

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

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值