Reputation: 887
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
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
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