我有一个 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'.
最佳答案
如果可以将其中一种类型转换为另一种类型,则可以使用 Except和 Intersect ,例如:
listOfOnes.Except(listOfTwos.Cast<One>())
否则,您可以测试第一个列表中的每个元素是否等于第二个列表中的任何元素:
var notInTwos = listOfOnes.Where(one =>
!listOfTwos.Any(two => two.Equals(one)));
虽然这不会那么快。
关于c# - 如何获取列表中和不在列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2595449/