Search code examples
c#linq

How can I change this code block to LINQ?


Since the for each loop will iterate so many times, I want to remove the foreach loop from the code. Can I change this to LINQ?

if (frameAndExportRequest.SearchObjectRequest.ObjectSearchFilterDetails
   .Any(field => field.FieldName == "APPROVED_BY_USER_NAME")) 
{
    foreach (var field in frameAndExportRequest.SearchObjectRequest.ObjectSearchFilterDetails) 
    {
        if (field.FieldName == "APPROVED_BY_USER_NAME") 
        {
            field.FieldName = "APPROVED_BY_USER";
        }
    }
}

Solution

  • If there is at most 1 match to be expected then you can use LINQ .FirstOrDefault():

    var field = frameAndExportRequest
        .SearchObjectRequest
        .ObjectSearchFilterDetails
        .FirstOrDefault(f => f.FieldName == "APPROVED_BY_USER_NAME");
    
    if (field != null)
        field.FieldName = "APPROVED_BY_USER";
    

    If there could be multiple matches, then you need to use .Where():

    var fields = frameAndExportRequest
        .SearchObjectRequest
        .ObjectSearchFilterDetails
        .Where(f => f.FieldName == "APPROVED_BY_USER_NAME")
        .ToList();
    
    fields.ForEach(f => f.FieldName = "APPROVED_BY_USER"); // or use built-in foreach
    

    Or use foreach from the start:

    foreach (var field in frameAndExportRequest.SearchObjectRequest.ObjectSearchFilterDetails
        .Where(f => f.FieldName == "APPROVED_BY_USER_NAME"))
    {
        field.FieldName = "APPROVED_BY_USER";
    }
    

    Note that either you do a foreach, or LINQ does it (or something similar) behind the scenes. There will always be a loop - even in the FirstOrDefault case, only then it could do an early exit, so it could be a bit more efficient than the others if you expect at most one match.