使用StartsWith将值与字符串数组进行比较

13

我有一个数组:

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不以异常数组中的某个值为起始。我知道StartsWith不能接受一个集合,所以我不确定是否可以通过LINQ实现。

在LINQ中是否可能实现这一点?还是我试图让我的问题适应于一个LINQ解决方案?

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

5个回答

17
var result =  myCollection.Where(c =>  
                           exceptions.All(e => 
                                       !c.Property[3].Value.StartsWith(e));

1
这个对我来说第一次就起作用了,而且只有一行代码。谢谢。 - pierre
查询返回属性不以任何异常字符串开头的集合,!Any() 返回 true,即使一个属性没有单个异常,但我们需要确保所有异常都符合要求,我相信在单词“ANY”上存在一些混淆。 - sll
@pierre:很高兴听到这个消息,我建议前瞻性地通过单元测试来覆盖这样的逻辑。 - sll
2
使用 All 永远不会返回任何结果。应该使用 Any - Enigmativity
看起来有些混淆,我们必须问OP他的工作是什么。 - sll
显示剩余4条评论

3
你可以使用IndexOfAny(并检查结果是否为索引位置零),因为它接受一个集合作为参数。

3

试试这个:

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;

0
var result = myCollection
              .where(
                 rs=>exceptions
                 .where(
                     rs1=>!rs.property[3].value.startsWith(rs1)
                  )
              )

0

您可以选择不需要的项目集合,然后执行 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)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接