Home > Software design >  LINQ Any an array to predicate an array whether it consists of the text of the first array
LINQ Any an array to predicate an array whether it consists of the text of the first array

Time:03-31

I would like to check whether first array match with second array items, the second array have 2 text that I want to match with the first array.

Here is the code that I am using:

public static void Main()
{
    List<string> ArrayToLookup = new List<string>();
    
    ArrayToLookup.Add("Web Junior Developer");
    ArrayToLookup.Add("Database Junior Specialist");
    
    string[] JuniorJobPosition = { "Junior Developer", "Junior Specialist" };
    string[] SeniorJobPosition = { "Senior Developer", "Senior Specialist" };
    
    string JobPositionText = JobPosition.None.ToString();
    
    if (ArrayToLookup.Any(x => JuniorJobPosition.Contains(x)))
        JobPositionText = JobPosition.JuniorPosition.ToString();

    if (ArrayToLookup.Any(x => SeniorJobPosition.Contains(x)))
        JobPositionText = JobPosition.SeniorPosition.ToString();
    
    Console.WriteLine(JobPositionText);
}

public enum JobPosition
{
    None = 0,
    JuniorPosition = 1,
    SeniorPosition = 2,
    OtherPosition = 3
}

basically the second array consists of text that I want to match contains against the first array.. the first text in the first array could be any with Junior Developer behind the text or Junior Specialist, and the second array just to categorize. Means if first array have Web Junior Developer and Web Junior Specialist, it will match the JuniorJobPosition variable

.Net fiddle: https://dotnetfiddle.net/UjhEaY

Anyone knows on how to solve this?

Thank you

CodePudding user response:

refactor your Conditions to

  if (ArrayToLookup.Any(x => JuniorJobPosition.Contains(x)))
  {
    JobPositionText = JobPosition.JuniorPosition.ToString();
  }
  else if (ArrayToLookup.Any(x => SeniorJobPosition.Contains(x)))
  {
    JobPositionText = JobPosition.SeniorPosition.ToString();
  }
  else
  {
    JobPositionText = JobPosition.OtherPosition.ToString();
  }

alternatively you could check

  if (ArrayToLookup.Intersect (JuniorJobPosition). Any())
  {
    JobPositionText = JobPosition.JuniorPosition.ToString();
  }
  else if (ArrayToLookup.Intersect (SeniorJobPosition). Any())
  {
    JobPositionText = JobPosition.SeniorPosition.ToString();
  }
  else
  {
    JobPositionText = JobPosition.OtherPosition.ToString();
  }

CodePudding user response:

Recorrect previous answer as the requirement clarified.

You need to check whether the text (in the second array) consists of text in ArrayLookup. Any of it fulfills the result will return true.

if (ArrayToLookup.Any(x => JuniorJobPosition.Any(y => x.Contains(y))))
    JobPositionText = JobPosition.JuniorPosition.ToString();
        
if (ArrayToLookup.Any(x => SeniorJobPosition.Any(y => x.Contains(y))))
    JobPositionText = JobPosition.SeniorPosition.ToString();

Sample Program

  • Related