zalky
zalky

Reputation: 887

How to convert a file loop into LINQ?

I have a method as following:

public static GatewayClient GetCurGwClient(System.Net.IPAddress gwIP)
{
    for (int i = 0; i < listKateApiObjcts.Count; i++)
    {
        if (listKateApiObjcts[i].CurrentGatewayClient.Gateway.IpAddress.ToString() == 
            gwIP.ToString())
        {
            return listKateApiObjcts[i].CurrentGatewayClient;
        }
    }

    return null;
}

I want to use LINQ to simplify this piece of code but I couldn't do it properly.

Upvotes: 1

Views: 83

Answers (2)

SomeBody
SomeBody

Reputation: 8743

FirstOrDefault() returns the first element that fulfills a certain condition. If no element is found that fulfills the condition, the default value of the type is returned (null for reference types). Your code would look like this:

public static GatewayClient GetCurGwClient(System.Net.IPAddress gwIP)//string
{
    return listKateApiObjcts
      .FirstOrDefault(x => x.CurrentGatewayClient.Gateway.IpAddress.ToString() == gwIP.ToString())
     ?.CurrentGatewayClient;
}

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

You are looking for FirstOrDefault:

 public static GatewayClient GetCurGwClient(System.Net.IPAddress gwIP) { 
   return listKateApiObjcts
     .Select(item => item.CurrentGatewayClient) 
     .FirstOrDefault(client => client.Gateway.IpAddress.ToString() == gwIP.ToString());
 }

Upvotes: 6

Related Questions