Home > Mobile >  How to embed dynamic OR condition after WHERE statement in linq query c#
How to embed dynamic OR condition after WHERE statement in linq query c#

Time:10-26

I have a LINQ query like this:

    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,                                 
    };

I want to store "asd", "dsa", "123", "456" in an array, so is there a possibility to loop through on that array and make the comparing in all items after the WHERE clause dynamically?

CodePudding user response:

You can use .Any() with an array,

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,                                 
                });

In query form,

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,                                 
   };
  • Related