c# - 如何获取列表中和不在列表中的项目

标签 c# linq

我有一个 IEnumerable、listOfOnes 和一个 IEnumerable、listOfTwos。

假设我可以将 V 的对象与 T 的对象进行比较,我想找出哪些项目在 listOfOnes 中,但不在 listOfTwos 中。反之亦然。

例如:

        var listOfOnes = new List<One>
        {
            new One
            {
                name = "chris",
                type = "user"
            },
            new One
            {
                name = "foo",
                type = "group"
            },
            new One
            {
                name = "john",
                type = "user"
            },
        };

        var listOfTwos = new[]
        {
            new Two
            {
                name = "chris",
                type = "user"
            },
            new Two
            {
                name = "john",
                type = "user"
            },
            new Two
            {
                name = "the Steves",
                type = "group"
            }
        };


        var notInTwos; //= listOfOnes.FindDifferences(listOfTwos); 
        //find all objects not in listOfTwos. Should find 'foo'.

        var notInOnes; //= listOfTwos.FindDifferences(listOfOnes)
        //find all objects not in listOfOnes. Should find 'the Steves'.

最佳答案

如果可以将其中一种类型转换为另一种类型,则可以使用 ExceptIntersect ,例如:

listOfOnes.Except(listOfTwos.Cast<One>())

否则,您可以测试第一个列表中的每个元素是否等于第二个列表中的任何元素:

var notInTwos = listOfOnes.Where(one =>
    !listOfTwos.Any(two => two.Equals(one)));

虽然这不会那么快。

关于c# - 如何获取列表中和不在列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2595449/

相关文章:

C# 早期绑定(bind)和后期绑定(bind)概念

c# - C# 中的 Linq 查询和转换

c# - 如何将公共(public)属性添加到要在 web.config 中配置的自定义 SqlMembership Provider

c# - LINQ 语句中的多个 OR 子句

c# - 如何修复此 ArrayIndex 错误?

c# - 在 LINQ 语句中使用 async/await 时实际发生了什么?

C# Linq Query group by 检查结果是否为空

c# - 根据一个可以保存多个值的变量对数组进行排序

作为接口(interface)实现的 C# 扩展方法

c# - 嵌套字典大小增长