Home > Enterprise >  convert the for loop to lambda expressions in c#
convert the for loop to lambda expressions in c#

Time:10-17

How should I write using Lambda functions and make this to just one/two lines?

 public static SaaSWorkflowMatrix? GetPrevNode(this IList<SaaSWorkflowMatrix> coordinates, string username)
        {
            try
            {
                for (int i = 0; i < coordinates.Count; i  )
                {
                    if (coordinates[i].UserName == username)
                        return coordinates[i - 1];  // Need error checking
                }
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }

           
        }

I tried this

return coordinates[coordinates.FirstOrDefault(x => x.UserName == username).currentIndex -1];

but it didnot work

CodePudding user response:

You can try using FindIndex method

var index = coordinates.FindIndex(p => p.UserName == username); 

then if index is -1, not exist in the list something with UserName == username

CodePudding user response:

Reverse allows to iterate backwards, then the prev become the next.

SkipWhile allows to iterate until the element searched.

Skip allows to iterate to the next element (precedent if enumeration is reversed).

coordinates.Reverse().SkipWhile(u => u.UserName != username).Skip(1).First();

CodePudding user response:

try this

var result = coordinates.FindIndex(i=> i.UserName == username) > 0 ? coordinates[coordinates.FindIndex(i=> i.UserName == username) - 1] : null;
  • Related