简体   繁体   中英

Refactoring using LINQ, C# and Lists NetworkInterface

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 of listaDirecciones.Add(ip.Address.ToString()); just do yield return ip.Address.ToString() ) and let the caller decide if they need to convert it into a list.

You could replace your loop with the following code:

return new List<string>(
    from nic in interfacesActivos
    from ips in nic.GetIPProperties().UnicastAddresses
    select ip.Address.ToString());

Just change your last loop with:

return interfacesActivos.SelectMany(nic => nic.GetIPProperties().UnicastAddresses)
                        .Select(ip => ip.ToString())
                        .ToList();

EDIT:

As cdhowie said, you can skip the ToList<NetworkInterface>() .

Also, depending on your needs, you can skip the ToList() of my code snippet too, and just returning a IEnumerable<string>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM