我正在尝试检查List<int>
A是否包含List<int> B
但是,如果A是B的真实子集,我需要确保不仅值正确而且还有它们的计数。
我找到了这样的解决方案,但两者都给出了错误的答案:
List <int> A = new List <int>(){1,1,2,3};
List <int> B = new List <int>(){1,2,3,5,6,7,8,9};
bool c = A.All(B.Contains);
bool d = !A.Except(B).Any();
Console.WriteLine(c); //True
Console.WriteLine(d); //True
列表A不能是列表B的子集,因为它包含双值1;
如何处理重复值?
更多例子
A = {1,2,3};
B = {1,2,3,4,5};
A is a subset of B => True
A = {1,1,2,3,2};
B = {1,1,2,2,3,4,5};
A is a subset of B => True
A = {1,2,3};
B = {1,1,2,2,3,4,5};
A is a subset of B => True
但:
A = {1,2,2,3};
B = {1,2,3,4,5};
A is not a subset of B => False
答案 0 :(得分:0)
您可以执行以下操作来对值进行分组并检查计数。
var bCounts = B.GroupBy(x=>x).ToDictionary(g=>g.Key, g=>g.Count());
bool aIsSubsetOfB = A.GroupBy(x=>x)
.All(g => bCounts.ContainsKey(g.Key) && bCounts[g.Key] > g.Count());
答案 1 :(得分:0)
根据您的样本,我了解您要保留重复内容.... 尝试如下所述....
List<int> a = new List<int> { 1, 2, 2, 3 };
List<int> b = new List<int> { 1, 2, 3, 4, 5,2};
IEnumerable<int> both = Intersect2(a,b);
if (a.Count() == both.Count())
{
int i1 = 0;
//Subset
}
Intersect2方法如下所示
public static IEnumerable<T> Intersect2<T>(IEnumerable<T> source, IEnumerable<T> target)
{
List<T> list = target.ToList();
foreach (T item in source)
{
if (list.Contains(item))
{
list.Remove(item);
yield return item;
}
}
}