检查列表1中的所有元素是否<;T>;在列表2中<;T>;C#
是否可以知道或检查列表1中的所有元素是否都是列表2的一部分? 举个例子检查列表1中的所有元素是否<;T>;在列表2中<;T>;C#,c#,list,C#,List,是否可以知道或检查列表1中的所有元素是否都是列表2的一部分? 举个例子 List1 = { 1,2,3,4 } List2 = { 1,2,3,5,6,4 } 如果列表1中的所有元素都在列表2中,我希望得到True,否则为False 注:无ForLoop 列表可以是整数、字符串等的列表使用LINQ方法: using System.Linq; bool allInList2 = !List1.Except(List2).Any(); List1.Intersect(List2).Count
List1 = { 1,2,3,4 }
List2 = { 1,2,3,5,6,4 }
如果列表1中的所有元素都在列表2中,我希望得到True,否则为False
注:无ForLoop
列表可以是整数、字符串等的列表使用LINQ方法:
using System.Linq;
bool allInList2 = !List1.Except(List2).Any();
List1.Intersect(List2).Count() == List1.Count()
请注意,这可以归结为在两个列表上进行迭代-这是不可能的 你可以用这个方法
然后,如果结果的长度与List1
相同,则您知道它的所有元素都包含在List2
中List1=new List(){1,2,3,4};
bool value = !(l1.Any(item => !l2.Contains(item)));
List list2=新列表(){1,2,3,5,6,4};
list1.All(x=>list2.Contains(x));
创建这些列表中的一个,并仅查询该交叉点结果列表。当然,内部有一个循环(并且必须是任何给定的解决方案) HTH最佳性能LINQ解决方案 此代码示例
-检查b中是否有不在a中的任何元素
-然后反转结果
using System.Linq;
....
public static bool ContainsAllItems(List<T> a, List<T> b)
{
return !b.Except(a).Any();
}
使用System.Linq;
....
公共静态布尔项(列表a、列表b)
{
return!b.除了(a).Any();
}
最初找到的解决方案。您可以使用如下(或)方法:
var hashset1 = new HashSet<int>(list1);
if (hashset1.IsProperSubsetOf(list2)) ...
var hashset1=新的HashSet(列表1);
如果(hashset1.ispropertsubsetof(list2))。。。
扩展方法,长版本:
public static IsSubetOf (this IEnumerable coll1, IEnumerable coll2)
{
foreach (var elem in coll1)
{
if (!coll2.Contains (elem))
{
return false;
}
}
return true;
}
简短版本:
public static IsSubetOf (this IEnumerable<T> coll1, IEnumerable<T> coll2)
{
return !coll1.Any (x => !coll2.Contains (x));
}
publicstaticissubetof(此IEnumerable coll1,IEnumerable coll2)
{
return!coll1.Any(x=>!coll2.Contains(x));
}
如果没有for循环,您希望如何检查列表中的所有元素。。。使用LINQ或其他类似的技巧仍然可以归结为枚举每个元素。。。所以基本上是一个for循环!他不想要值
,但想要值的可能副本!值
作为结果;)如果list1的任何成员出现在list2中,或者我遗漏了什么,Haris-ur解决方案将返回true?请简化过于复杂的表达式:!list.Any(x=>condition)==list.All(x=>!condition)
Perfect,但我认为您在lambda上键入了list1,您必须将其更改为list2:list1.All(x=>list2.Contains(x));
public static IsSubetOf (this IEnumerable<T> coll1, IEnumerable<T> coll2)
{
return !coll1.Any (x => !coll2.Contains (x));
}