【问题标题】:How to embed dynamic OR condition after WHERE statement in linq query c#如何在 linq 查询 c# 中的 WHERE 语句后嵌入动态 OR 条件
【发布时间】:2021-12-02 14:58:33
【问题描述】:

我有一个这样的 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# arrays linq collections


    【解决方案1】:

    您可以将.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,                                 
       };
    

    【讨论】:

    • @dba,我的愚蠢错误。我已修复它,请查看更新的答案并感谢您的评论
    • 我确定,这只是一个错字,但我无法编辑,因此评论:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多