我有两个数组。我需要比较它们如下所示,结果应该是bool
Input :
Example 1
---------
stringArray1 = "one","five"
stringArray2 = "two","one" ,"three","five"
Result = true
Example 2
---------
stringArray1 = "one","five"
stringArray2 = "two","three" ,"four","five"
Result = false (As "one" is not present in array2)
string[] stringArray1 = getDataTabledFromSP.Columns.Cast<DataColumn>()
.OrderBy(x => x.ColumnName)
.Select(x => x.ColumnName)
.ToArray();
string[] stringArray2 = fetchColumnDetailsOfClientById
.OrderBy(x => x.ColumnName)
.Select(myLine => myLine.ColumnName).ToArray();
你可以尝试设置算术:
bool result = !stringArray1.Except(stringArray2).Any();
我们从stringArray2
中减去stringArray1
然后检查我们是否有任何项目(这是stringArray1
中没有的stringArray2
项目)。
编辑:如果stringArray1
和stringArray2
可以有重复项,应该考虑(例如,所有三个相同的项目应该在stringArray2
中找到):
bool result = !stringArray1
.GroupBy(item => item)
.Select(chunk => Tuple.Create(chunk.Key, chunk.Count()))
.Concat(stringArray2
.GroupBy(item => item)
.Select(chunk => Tuple.Create(chunk.Key, -chunk.Count()))
)
.GroupBy(item => item.Item1)
.Select(chunk => chunk.Sum(item => item.Item2))
.Any(item => item > 0);
如果你想检查一个数组的所有元素是否存在于另一个或All()
函数中,你可以使用Linq Any()
函数
stringArray2.All(x => stringArray1.Contains(x))
所以当true
包含stringArray2
中的每个项目时,你想要一些返回stringArray1
的东西吗?这应该做:
// Not any string which is not contained in the stringArray2
!stringArray1.Any(s => !stringArray2.Contains(s));