if语句的多个值

时间:2016-09-08 07:14:32

标签: c# list

如果我的陈述包含两个条件:

string searchx = "some string"; 

if ((searchx.Contains("a1")) || (searchx.Contains("a2")))
{
...
}

但是如何使用单个变量获取语句值列表?

如果我得到a1, a2, a3, a4, a5, a6, a7, a8, a9...

我可以这样做,似乎是错误的尝试:

var valueList = new List<string> { "a1", "a2", "a3", "a4"};

但只是为了解释我想要做什么,所以如果valueList下存在任何值,则接受条件:

if (searchx.Contains(valueList)) 
{
...
}

最好,如果我可以得到多个值返回我猜或任何其他方式通过任何其他方式的单个变量获取更新的值列表的语句,这可以这样对我有用吗?

5 个答案:

答案 0 :(得分:8)

这对我有用:

if (valueList.Any(x => searchx.Contains(x)))
{
}

甚至更短(感谢rajeeshmenoth)

    if(valueList.Any(searchx.Contains))

答案 1 :(得分:3)

您可以尝试使用Except

if (valueList.Except(searchx).Any())
{

}

答案 2 :(得分:1)

不是最好的解决方案,但有效。

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    lodash = require('lodash'),
    data = require('gulp-data'),
    filesize = require('gulp-filesize'),
    filter = require('gulp-filter'),           // ADDED
    frontMatter = require('gulp-front-matter'),
    rename = require('gulp-rename'),
    util = require('util');

gulp.task('metalsmith', function() {
    const filterPHP = filter('blog/**/*', { restore: true });
    const filterHTML = filter('!blog/**/*', { restore: true });
    return gulp.src(CONTENT_DIR)

                                                  //---- if the only purpose of this particular gulp-front-matter pipe was to support the extension assignment, you could drop it
        .pipe(frontMatter()).on("data", function(file) {    //
            lodash.assign(file, file.frontMatter);          //
            delete file.frontMatter;                        //
        })                                                  //
                                                 //---------

        .pipe(filterPHP)                    // narrow down to just the files matched by filterPHP
        .pipe(rename({ extname: '.php' }))
        .pipe(filterPHP.restore)           // widen back up to the full gulp.src
        .pipe(filterHTML)                  // narrow down to just the files matched by filterHTML
        .pipe(rename({ extname: '.html' }))
        .pipe(filterHTML.restore)          // widen back up
        .pipe(gulp.dest(BUILD_DIR))
});

并使用它:

bool containsValue(string search)
{
var valueList = new List<string> { "a1", "a2", "a3", "a4"};
foreach (string s in valueList)
 {
 if(search.Contains(s))
  return true;
 }
return false;
}

答案 3 :(得分:0)

您可以使用Linq:

  bool b = valueList.Any(searchx.Contains);

试试这个:

    string searchx = "a8"; 
    var valueList = new List<string>{"a1", "a2", "a3", "a4"};

    if (valueList.Any(searchx.Contains))
        Console.WriteLine("Data Matching..!!");
    else
        Console.WriteLine("Not Matching..!!");

演示: Click here

答案 4 :(得分:-1)

你可以制作一个foreach循环

string search = "GIVE A STRING";
List<string> DataList = new List<string> {"a1", "a2", "a3",.....};
foreach(string Data in DataList)
{ 
  if(search.Contains(Data))
  { //TODO }
}