首页 > 解决方案 > 如何在 linq 查询 c# 中的 WHERE 语句后嵌入动态 OR 条件

问题描述

我有一个这样的 LINQ 查询:

    var getOnlyMP = from mpPoint in cmList where 
    mpPoint.Component.Contains("asd") || 
    mpPoint.Component.Contains("dsa") || 
    mpPoint.Component.Contains("123") || 
    mpPoint.Component.Contains("456")                                            
    select new MP
    {
        MPName = mpPoint.Component,
        X = mpPoint.PlaceX,
        Y = mpPoint.PlaceY,                                 
    };

我想将“asd”、“dsa”、“123”、“456”存储在一个数组中,那么是否有可能在该数组上循环并动态比较 WHERE 子句之后的所有项目?

标签: c#arrayslinqcollections

解决方案


您可以.Any()与数组一起使用,

var expectedStrings = new string[] {"asd", "dsa", "123", "456"};

var getOnlyMP = cmList.Where(mpPoint=> 
        expectedStrings.Any(x => mpPoint.Component.Contains(x)))
        .Select(x => new MP
                {
                   MPName = x.Component,
                   X = x.PlaceX,
                   Y = x.PlaceY,                                 
                });

在查询形式中,

var expectedStrings = new string[] {"asd", "dsa", "123", "456"};
var getOnlyMP = from mpPoint in cmList where 
   expectedStrings.Any(x => mpPoint.Component.Contains(x)))             
   select new MP
   {
      MPName = mpPoint.Component,
      X = mpPoint.PlaceX,
      Y = mpPoint.PlaceY,                                 
   };

推荐阅读