I want use only LINQ statement for the following method. I return List of strings, but first I get List of NetworkInterface.
public static List<string> ObtenerDireccionesDeInterfacesDeRedActivos()
{
var listaDirecciones = new List<string>();
var interfacesActivos =
(from networkInterface in NetworkInterface.GetAllNetworkInterfaces()
let
/*IPv4InterfaceStatistics*/
statistics = networkInterface.GetIPv4Statistics()
where
// filter so we see only Internet adapters
networkInterface.OperationalStatus == OperationalStatus.Up
&& networkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel
&& networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback
// all testing seems to prove that once an interface comes online
// it has already accrued statistics for both received and sent...
&& (statistics.BytesReceived > 0) && (statistics.BytesSent > 0)
select
networkInterface).ToList<NetworkInterface>();
foreach (NetworkInterface nic in interfacesActivos)
{
var ips = nic.GetIPProperties().UnicastAddresses;
foreach (var ip in ips)
{
listaDirecciones.Add(ip.Address.ToString());
}
}
return listaDirecciones;
}
any suggestions ?
The
ToList<NetworkInterface>()call is unnecessary. There is no reason why you should have to turn this query into a list before enumerating it.Additionally, you might consider having this method return an
IEnumerable<string>(instead oflistaDirecciones.Add(ip.Address.ToString());just doyield return ip.Address.ToString()) and let the caller decide if they need to convert it into a list.