gpt4 book ai didi

c#-4.0 - 验证两个列表是否在 C# 中共享值

转载 作者:行者123 更新时间:2023-12-04 00:42:23 26 4
gpt4 key购买 nike

在应用交集之前,我想知道两个列表是否共享值。像 bool DoIntersect(listA, listB) 这样的东西会很棒!

这是我想出的代码:

// Person is a class with Id and Name properties
List<Person> people1;
List<Person> people2;

// Populate people1 and people2...

// My current solution (pseudocode obviously)...

if (DoIntersect(people1, people2))
{
people1 = people1.Intersect(people2)
}
else
{
/* No shared people */
throw exception;
}

// Continue with the process...

最佳答案

这完全取决于你想要什么:

// are there any common values between a and b?
public static bool SharesAnyValueWith<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return a.Intersect(b).Any();
}

对于不重叠的列表,这将遍历 a 和 b 各一次。对于重叠的列表,这将一直遍历 a,然后遍历 b,直到找到第一个重叠元素。

// does a contain all of b? (ignores duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return !b.Except(a).Any();
}

这将遍历 a 一次,然后遍历 b,停止在 b 中的第一个元素而不是 a 中。

// does a contain all of b? (considers duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
// get the count of each distinct element in a
var counts = a.GroupBy(t => t).ToDictionary(g => g.Key, g => g.Count());
foreach (var t in b) {
int count;
// if t isn't in a or has too few occurrences return false. Otherwise, reduce
// the count by 1
if (!counts.TryGetValue(t, out count) || count == 0) { return false; }
counts[t] = count - 1;
}

return true;
}

类似地,这将遍历 a 一次,然后遍历 b,停止在 b 中的第一个元素而不是 a 中。

关于c#-4.0 - 验证两个列表是否在 C# 中共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17506753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com