我面临以下问题:
我想比较两个列表,以了解ListA是否包含所有ListB的项目。
我也想对它们进行计数,以便获得缺少的元素数量(如果有)。
是否有一种简单的方法来实现这一目标?
public static bool ContainsAllItems<T>(IEnumerable<T> a, IEnumerable<T> b)
{
return !b.Except(a).Any();
}
预期
public static int ContainsAllItems<T>(IEnumerable<T> a, IEnumerable<T> b)
{
//Count how much Elements are missing or if there are some missing
return count(!b.Except(a).Any());
}
答案 0 :(得分:3)
您可以使用Linq Count()
方法来获取列表b
中存在但列表a
中缺少的元素计数
返回序列中的元素数。
var count = b.Except(a).Count();
您的代码看起来像
//Get count of elements which are present in List b, but missing in List a
public static int ContainsAllItems<T>(IEnumerable<T> a, IEnumerable<T> b)
{
return b.Except(a).Count();
}