检查字符串数组1中的项是否存在于字符串数组2中并返回bool

时间:2019-02-28 07:48:37

标签: c# arrays linq string-comparison

我有两个数组。我需要将它们进行如下比较,结果应为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();

3 个答案:

答案 0 :(得分:1)

您可以尝试 set 算术:

 bool result = !stringArray1.Except(stringArray2).Any();

我们从stringArray2减去 stringArray1,然后检查是否有任何项目(stringArray1中没有stringArray2的项目)。

编辑:如果stringArray1stringArray2可以具有重复,应将其考虑在内(例如,所有三个 >应该在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);

答案 1 :(得分:0)

因此,当true包含stringArray2中的每个项目时,您是否想要返回stringArray1的东西? 应该这样做:

// Not any string which is not contained in the stringArray2
!stringArray1.Any(s => !stringArray2.Contains(s));

答案 2 :(得分:0)

如果要检查一个数组的所有元素是否都存在于另一个数组中,或者可以使用val spark = SparkSession .builder .appName("test") .config("spark.local", "local[*]") .getOrCreate() spark.sparkContext.setCheckpointDir(path_checkpoint) val event1 = spark .readStream // .schema(schema_a) .option("header", "true") .option("sep", ",") .csv(path_a) val query = event1.writeStream .outputMode("append") .format("console") .start() spark.streams.awaitAnyTermination() 函数,例如

,可以使用Linq All()函数
Any()