Mat*_*ley 91 .net c# generics mono list
我有以下方法:
namespace ListHelper
{
public class ListHelper<T>
{
public static bool ContainsAllItems(List<T> a, List<T> b)
{
return b.TrueForAll(delegate(T t)
{
return a.Contains(t);
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
其目的是确定List是否包含另一个列表的所有元素.在我看来,这样的东西已经内置到.NET中,就是这样,我是否复制了功能?
编辑:我很抱歉没有说明我在Mono版本2.4.2上使用此代码.
Jon*_*eet 166
如果您使用的是.NET 3.5,那很简单:
public class ListHelper<T>
{
public static bool ContainsAllItems(List<T> a, List<T> b)
{
return !b.Except(a).Any();
}
}
Run Code Online (Sandbox Code Playgroud)
这将检查是否有任何元素b不在a- 然后反转结果.
请注意,使方法通用而不是类更常规,并且没有理由要求List<T>而不是IEnumerable<T>- 所以这可能是首选:
public static class LinqExtras // Or whatever
{
public static bool ContainsAllItems<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return !b.Except(a).Any();
}
}
Run Code Online (Sandbox Code Playgroud)
drz*_*aus 33
只是为了好玩,@ JonSkeet 作为扩展方法的答案:
/// <summary>
/// Does a list contain all values of another list?
/// </summary>
/// <remarks>Needs .NET 3.5 or greater. Source: https://stackoverflow.com/a/1520664/1037948 </remarks>
/// <typeparam name="T">list value type</typeparam>
/// <param name="containingList">the larger list we're checking in</param>
/// <param name="lookupList">the list to look for in the containing list</param>
/// <returns>true if it has everything</returns>
public static bool ContainsAll<T>(this IEnumerable<T> containingList, IEnumerable<T> lookupList) {
return ! lookupList.Except(containingList).Any();
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*mas 31
包含在.NET 4中: Enumerable.All
public static bool ContainsAll<T>(IEnumerable<T> source, IEnumerable<T> values)
{
return values.All(value => source.Contains(value));
}
Run Code Online (Sandbox Code Playgroud)