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

时间:2010-04-07 19:53:11

标签: 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'.

2 个答案:

答案 0 :(得分:6)

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

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

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

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

但这不会那么快。

答案 1 :(得分:1)

也许像

public static IEnumerable<T> FindDifference<U> (
    this IEnumerable<T> a, 
    IEnumerable<U> b,
    Func<T, U> convert)
{
    IEnumerable<T> bConvertedToT = b.Select (item => convert (item));
    IEnumerable<T> aNotInB = a.Except (bConvertedToT);
    return aNotInB;
}