【问题标题】:Check string array 1 items are present in string array 2 and return bool检查字符串数组 1 项是否存在于字符串数组 2 中并返回 bool
【发布时间】:2019-02-28 07:48:36
【问题描述】:

我有两个数组。我需要比较它们,如下所示,结果应该是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();

【问题讨论】:

  • 提示:stringArray2.Contains(str)
  • !stringArray1.Except(stringArray2).Any()

标签: c# arrays linq string-comparison


【解决方案1】:

你可以试试set算术:

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

我们从stringArray1减去 stringArray2,然后检查我们是否有任何项目(这是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);

【讨论】:

    【解决方案2】:

    如果要检查一个数组的所有元素是否存在于另一个数组中,可以使用 Linq All() 函数或 Any() 函数类似

    stringArray2.All(x => stringArray1.Contains(x))
    

    【讨论】:

    • 作为O(N * M)(时间复杂度)算法,在长stringArray1stringArray2数组的情况下可能效率低
    【解决方案3】:

    那么当stringArray2 包含stringArray1 中的所有项目时,您是否想要返回true 的东西? 应该这样做:

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

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2021-12-27
      • 2022-01-10
      相关资源
      最近更新 更多