Need LINQ query to search a list of string in a list of input values

Viewed 77

Suppose i have to search in inputValues list which are started with list of codes. I have done it with the help of foreach loop. But I need to did the same using LINQ:

List<string> inputValues = new List<string> {
    "S083*01999900FN0060000.000001097.00000.0020020101",
    "S013*01999900FN0060000.100001097.00000.0020020101",
    "S529*01999900FN0060000.999001097.00000.0020020101",
    "S530*01999900FN0060000.222001097.00000.0020020101",
    "S530*45199900FMo060000.222001097.00000.0020020101",
    "S541*01999900FN0060000.999001097.00000.0020020101",
    "S519*01999900FN0060000.999001097.00000.0020020101",
    "S099*01999900FN0060000.999001097.00000.0020020101",
};

List<string> codes = new List<string> { 
    "S099", "S529", "S530", "I897",
};

private static List<string> GetValidList(List<string> inputValues, 
                                         List<string> codes)
{
    List<string> result=new List<string>();
        
    foreach( string item in inputValues)
    {
        foreach(string code in codes)
        {
            if (item.StartsWith(code))
                result.Add(item);
        }
    }

    return result;
}
1 Answers

Linq query can be like this:

var result = inputValues
  .Where(value => codes.Any(code => value.StartsWith(code)))
  .ToList(); 

Here we for each value from inputValues check if there's a code from codes such that value starts from this code

Method

private static List<string> GetValidList(List<string> inputValues, 
                                         List<string> codes) => inputValues
  .Where(value => codes.Any(code => value.StartsWith(code)))
  .ToList(); 

Edit: If we want to return duplicates when codes have duplicates (see Harald Coppoolse's comment) we can put SelectMany

private static List<string> GetValidList(List<string> inputValues,
                                         List<string> codes) => codes
  .SelectMany(code => inputValues.Where(value => value.StartsWith(code)))
  .ToList();
Related