Venkat
Venkat

Reputation: 2156

convert the for loop to lambda expressions in c#

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

Upvotes: 0

Views: 46

Answers (3)

Serge
Serge

Reputation: 43880

try this

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

Upvotes: 1

vernou
vernou

Reputation: 7590

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();

Upvotes: 1

Mauxricio
Mauxricio

Reputation: 190

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

Upvotes: 3

Related Questions