Search code examples
c#winformslinqnetwork-interface

Use LINQ for AddRange to Listbox


Hello I try To Convert My old code to new version with Linq but i have problem for do it old :

foreach (var item in NetworkInterface.GetAllNetworkInterfaces())
{
    if (item.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
    {
        lstTrace.Items.Add(item.Name);
    }
}

to this:

lstTrace.Items.Add(
    NetworkInterface.GetAllNetworkInterfaces()
        .Where(nic => nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
        .FirstOrDefault()
        .Name
);

But it just returns one result. How can I get all found items?


Solution

  • I would not recommend to create 'one-liner' code which spans for 5 lines and mixes both data selection and filling list view. Make both things easy to read and understand. Split (1) retrieving and filtering data with (2) assigning data to list view:

    var ethernetInterfaceNames = 
           from i in NetworkInterface.GetAllNetworkInterfaces()
           where i.NetworkInterfaceType == NetworkInterfaceType.Ethernet
           select i.Name;
    
    foreach(var name in ethernetInterfaceNames)
        lstTrace.Items.Add(name);
    

    I would also move getting ethernet interface names to separate method or layer. Thus you will split business logic and presentation logic. You can use AddRange here, but it willl not make your code any simpler:

    lstTrace.Items.AddRange(ethernetInterfaceNames.Select(n => new ListViewItem(n)).ToArray())
    

    I believe simple foreach loop is far more readable.