问题描述
检查List<List<int>>
是否包含List<int>
的最佳方法是什么:
What is the best way to check if a List<List<int>>
contains a List<int>
like:
List<List<int>> test = new List<List<int>>();
List<int> a = new List<int>{1,2,3,4,5,6};
List<int> b = new List<int>{1,2,3,4,5,6};
test.Add(a);
Debug.Log(test.Contains(b));
我知道Contains()
不会检查List<T>
的内容,所以我正在寻找一种确定等效性的替代方法.
I know that Contains()
doesn't check the contents of List<T>
, so I'm looking for an alternative way to determine equivalence.
推荐答案
尝试一下:
test.Any(x => x.All(b.Contains));
这将返回true
,但并不完全正确.如果b
包含的元素多于1,2,3,4,5,6
(例如,7,8,9
等),它也会返回true
.要解决此问题,您可以尝试SequenceEqual
:
This will return true
but it's not exactly correct. It would also return true
if b
contains more elements than 1,2,3,4,5,6
(for example 7,8,9
, etc). To fix this you can try SequenceEqual
:
test.Any(x => x.OrderBy(y => y)
.SequenceEqual(b.OrderBy(z => z)));
如果您不希望它在b
无序(例如2,1,3,4,5,6
)无序时返回true
,则不要使用OrderBy
;否则,请使用OrderBy
.只需使用SequenceEqual
:
If you don't want it to return true
when b
is unordered (for example 2,1,3,4,5,6
), then don't use OrderBy
; just use SequenceEqual
:
test.Any(x => x.SequenceEqual(b));
这篇关于检查List< List< int>>包含List< int>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!