[英]Can I use LINQ to compare ranges in two arrays?
I can roll a method, pseudo:我可以滚动一个方法,伪:
bool Compare(IList left, int lIndex, IList right, int rIndex, int num)
{
for(int i=0;i<num;++i)
{
if(left[lIndex+i] != right[rIndex+i])
{
return false;
}
}
return true;
}
So given L =[1,2,3,4,5,6,7,8]
and R = [5,6,7,8,9]
: Compare(L,5,R,1,3) == true
所以给定L =[1,2,3,4,5,6,7,8]
和R = [5,6,7,8,9]
: Compare(L,5,R,1,3) == true
I feel I should be able to do a simple LINQ version but I am not sure how to handle the indexing.我觉得我应该能够做一个简单的 LINQ 版本,但我不确定如何处理索引。 Can it be written as a trivial LINQ/lambda... otherwise I'll pull this out as a utility method.它可以写成一个微不足道的 LINQ/lambda... 否则我会把它作为一种实用方法来提取。
By the way there is a question with a very similar title but it is asking a different thing: https://stackoverflow.com/questions/33812323/compare-two-arrays-using-linq顺便说一句,有一个标题非常相似的问题,但它问的是另一件事: https://stackoverflow.com/questions/33812323/compare-two-arrays-using-linq
You can Skip
, Take
, and SequenceEqual
:您可以Skip
、 Take
和SequenceEqual
:
return left.Skip(lIndex).Take(num).SequenceEqual(
right.Skip(rIndex).Take(num))
Note that you should make your Compare
method generic and use the generic IList<T>
instead.请注意,您应该使您的Compare
方法通用,并改用通用IList<T>
。
you can try this你可以试试这个
int num = 3,lIndex =5,rIndex =1;
var L = (new List<int>(){1,2,3,4,5,6,7,8}).Skip(lIndex).Take(num).ToList();
var R = (new List<int>(){5,6,7,8,9}).Skip(rIndex).Take(num).ToList();
var result = L.Count() == R.Count() && !R.Except(L).Any() && !L.Except(R).Any() && string.Join(",",L).Equals(string.Join(",",R));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.