【问题标题】:Compare value to array of strings using StartsWith使用 StartsWith 将值与字符串数组进行比较
【发布时间】:2012-01-04 15:59:59
【问题描述】:

我有一个数组:

string[] exceptions = new string[] { "one", two", "one_1", "three" };

..我想说:

var result = from c in myCollection
             where not c.Property[3].Value.StartWith(exceptions)
             select c;

所以我希望过滤 myCollection 以仅显示那些 Property[3].Value 在异常数组中 StartWith 的值。我知道 StartsWith 不会收集,所以我不确定这是否可以通过 LINQ 实现。

这在 LINQ 中可能吗?!还是我试图将我的问题硬塞到 LINQ 解决方案中?

编辑:我应该说,包含不是一个选项,因为我只想排除属性以异常字符串开头的元素。

【问题讨论】:

    标签: c# .net arrays linq comparison


    【解决方案1】:
    var result =  myCollection.Where(c =>  
                               exceptions.All(e => 
                                           !c.Property[3].Value.StartsWith(e));
    

    【讨论】:

    • 这个第一次为我工作,是一个单线。谢谢。
    • 查询返回的集合的属性不以任何异常字符串开头,!Any() 即使属性不以单个异常开头也返回 true 但我们需要确保所有异常都如此,我相信有一些与词混淆ANY
    • @pierre : 很高兴听到,我建议通过单元测试来覆盖这样的逻辑
    • 使用All 它永远不会返回任何结果。应该是Any
    • 看起来有些混乱,我们得问问 OP 什么对他有用
    【解决方案2】:

    试试这个:

    string[] exceptions = new string[] { "one", "two", "one_1", "three" };
    
    var result = from c in myCollection
                where !exceptions.Any(exception =>
                    c.Property[3].Value.StartsWith(exception))
                select c;
    

    【讨论】:

      【解决方案3】:

      您可以使用 IndexOfAny(检查结果是索引位置为零),因为它需要一个集合。

      【讨论】:

        【解决方案4】:

        您可以选择不想要的项目集合,然后执行 IEnumerable.Except()。

        我应该是这样的:

        var result = from c in myCollection               
                     where not c.Property[3].Value.StartWith(exceptions)               
                     select c;  
        
        var finalResult = myCollection.Except(myCollection.Select(i => i.StartWith(exception)));
        

        【讨论】:

          【解决方案5】:
          var result = myCollection
                        .where(
                           rs=>exceptions
                           .where(
                               rs1=>!rs.property[3].value.startsWith(rs1)
                            )
                        )
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-22
            • 2016-10-17
            • 2021-06-28
            • 1970-01-01
            相关资源
            最近更新 更多