有没有办法在C#中获得两组对象之间的差异 [英] Is there a way to get the difference between two sets of objects in c#

查看:74
本文介绍了有没有办法在C#中获得两组对象之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c#中获得两组int之间的差异.给定s1和s2,我想返回那些在s1中而不在s2中的整数.我可以做一些事情,例如:

I want to get the difference between two sets of ints in c#. Given s1 and s2 I want to return those ints which are in s1 and not in s2. I can do something such as:

    List<int> s1 = new List<int>();
    List<int> s2 = new List<int>();

    foreach (int i in s1)
    {
        if (s1.Contains(i))
        {
            //
        }
        else
        {
            //
        }
    }

但是我想知道是否有人可以指出任何更清洁的方法.我想做诸如

But I was wondering if anyone can point out anything cleaner. I would like to do something such as

List<int> omitted = s1.Difference(s2);

不确定是否存在任何人都可以指出的现有方法或LINQ构造?谢谢.

Not sure if there is an existing method or a LINQ construct that anyone might be able to point out? Thank you.

推荐答案

我认为您想要

I think you want HashSet.Except. That is, rather than use Lists, use HashSets, and then the operation is available. This is a better type if what you are representing is really a 'set' anyway. (If you already have a list, you can just create a 'new HashSet' out of it.)

这篇关于有没有办法在C#中获得两组对象之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆