linq检查多个条件中返回false的条件

时间:2017-06-14 07:18:58

标签: linq

我有以下代码示例:

List<string> temp = new List<string>();
temp.Add("bla bla");
temp.Add("111");
temp.Add("222");
temp.Add("1111111");
temp.Where(x => x.Length <= 5 && x.Contains("1")).ToList();

我希望结果:

元素:

[0] - &#34; bla bla&#34; - 结果为false - 在长度&lt; = 5

的条件下崩溃

[1] - &#34; 111&#34; - 结果是真的

[2] - &#34; 222&#34; - 结果为false - 在条件 x时崩溃。包含(&#34; 1&#34;)

[3] - &#34; 1111111&#34; - 结果为false - 在长度&lt; = 5

的条件下崩溃

我可以以某种方式做到吗?

2 个答案:

答案 0 :(得分:1)

通过在单独的列表中分割标准(如Func<string,bool s),您可以测试每个单独的设置。更进一步,通过将它们包装为Expression<>,可以获得(失败的)标准的内容:

List<string> temp = new List<string>{"bla bla", "111","222","1111111"};

var criteria = new Expression<Func<string,bool>>[]{x => x.Length <= 5 , x => x.Contains("1")}
    .Select(c=>new{Test=c.Compile(), Name = c.ToString()}).ToList(); //get precompiled lambdas with their names, based on the lambda expressions

var results = from s in temp    
    let fail = criteria.FirstOrDefault(c=>!c.Test(s)) //get the first criterium to fail (if any)
    select new {Value = s, Result = fail ==null , FailedOn = fail?.Name};


foreach(var m in results) //test output
    Console.WriteLine("Value: {0} [{1}] {2}" , m.Value, m.Result, m.Result ? null : " crashed on " + m.FailedOn);

上述结果:

  • 值:bla bla [False]在x =&gt;上崩溃(x.Length&lt; = 5)
  • 价值:111 [真]
  • 值:222 [False]在x =&gt;上崩溃x.Contains(&#34; 1&#34)
  • 价值:1111111 [错误]在x =&gt;上崩溃(x.Length&lt; = 5)

答案 1 :(得分:0)

当我检查你的代码时,它正确执行并给出正确的结果

List<string> temp = new List<string>();
            temp.Add("bla bla");
            temp.Add("111");
            temp.Add("222");
            temp.Add("1111111");
            var result= temp.Where(x => x.Length <= 5 && x.Contains("1")).ToList();

            foreach(var item in result)
            {
                Console.WriteLine("x={0}", item);
            }

enter image description here

如果你想返回true,你可以使用以下内容:  var result1 = temp.Where(x =&gt; x.Length&lt; = 5&amp;&amp; x.Contains(&#34; 1&#34;))。选择(x =&gt; true).ToList();