【问题标题】:Compare List<String[]> With Multiple Conditions比较 List<String[]> 与多个条件
【发布时间】:2012-10-04 19:51:58
【问题描述】:

我有两个List&lt;String[]&gt;'s(字符串数组列表),我想通过某些条件将内容相互匹配,以便最终结果返回 true 或 false。

List<string> TestA= {"A001","A002","A003","B001","B001","C003","D000","E001"};

List<string> TestB= {"A001","A002","A003","B999","C003"};

我想为以下条件编写一个函数。

  1. 如果TestA的所有项目都与TestB匹配(在TestA中相同的项目可以多次[例如B001])==>返回true
  2. 如果 TestB 包含任何具有数字 999 [Ex B999] 的项目,则无需循环在 testA 中以 B 开头的项目(此设置为 true),并且 TestA 的循环从 C003 开始​​ [在这种情况下,我认为我们需要删除如果 ListB 包含 B999,则 ListA 中 B 的所有项目]。 继续.. 所以循环运行TestA项目C003。这与 TestB 中的项目匹配再次设置为 true 现在,对于 D000 与 ListB 中不匹配的项目,现在终于将 bool 设置为 false 并中断。

【问题讨论】:

  • 欢迎使用 stackoverflow。你试过什么?
  • 我尝试了很多方法 ==> 嵌套循环,但我想要一些好的建议。
  • 现在我没有代码和链接,因为 Royi 分享了它在列表之间的唯一比较。但我想跳过 ListA 中的所有特定项目 [例如。 like B items] loop if in ListB Item Contains B999...kindda示例
  • 我很困惑,你有一个字符串数组列表(如你的开场白所示)还是有一个字符串列表(代码示例似乎表明)?

标签: c# asp.net linq


【解决方案1】:

这就是使用 LINQ 所需的全部内容:

// Condition 2:
// Get the characters of in list B that contains the "999" string. 
var badOnes = ListB.Where(s=>s.Contains("999").Select(s=>s[0])

// If there is any forbidden characters remove them from List A
if (badOnes.Length > 0)
{
    ListA.RemoveAll(x => x[0] == badOnes.Exists(c => c == x));
}

// Condition 1:
if (ListA.Distinct().Intersect(ListB).Length == ListA.Distinct().Length)
{
    return true;
}

希望这会有所帮助。

【讨论】:

  • 如果我的评论有帮助,请考虑将其标记为答案。
【解决方案2】:

不确定我是否理解,但请检查:

var filter = 
    from b in TestB
    where b.Contains("999")
    select b.Replace("999", "");

var cleaned = 
    from a in TestA
    where !filter.Any(f => a.StartsWith(f))
    select a;

var check = cleaned.Distinct()
                   .Except(TestB).Any();

编辑

根据您的进一步说明,我了解到您的前缀可能不止一个字母,因此我编辑了答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2011-12-11
    • 2014-12-03
    • 2014-04-25
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多