3
\$\begingroup\$

I made a list of all nearby printer devices (that match the same name in the database) as well as all printer devices from the database. They are separated in the list by "--". I am able to get the code running and working. However, it is slow. Nearby devices amount to roughly 10-15 expected but devices in the database are around 400.

I was wondering how can I refactor my code to make it cleaner, concise and more efficient (most important). Currently, it's a bit slow, so I add a process bar while I call this method in the background. It can take up to a few seconds to generate the entire list.

Here's my code:

public async Task<List<Models.Printer>> ListAllPrinters()
{
    //Gets all printers inside the Database 
    var printerDevices = await _deviceService.GetAllPrinters(); 

    //Gets all unpaired Bluetooth devices
    var unpairedDevices = BluetoothDevice.GetDeviceSelectorFromPairingState(false);

    //Gets all paired Bluetooth devices
    var pairedDevices = BluetoothDevice.GetDeviceSelectorFromPairingState(true);

    var unpairedNearDevices = (await DeviceInformation.FindAllAsync(unpairedDevices)).
        Select(x => x.Name).ToList();

    var pairedNearDevices = (await DeviceInformation.FindAllAsync(pairedDevices)).
        Select(x => x.Name).ToList();

    var nearbyDevices = unpairedNearDevices.Union(pairedNearDevices).ToList();

    List <Models.Printer> nearbyDevicesInDB = new List<Models.Printer>(); 
    List<Models.Printer> printers = new List<Models.Printer>();
    List<Models.Printer> printersList = new List<Models.Printer>();

        foreach (var printer in printerDevices)
        {
            printers.Add(new Models.Printer
            {
                SerialNumber = printer.SerialNumber,
                MacAddress = printer.MacAddress,
                IsInRange = false
            });

            //if nearby printer devices have the same name as device in database, then add it to nearbydevicesindb list 
            if (nearbyDevices.Contains(printer.SerialNumber))
            {
                nearbyDevicesInDB.Add(new Models.Printer
                {
                    SerialNumber = printer.SerialNumber,
                    MacAddress = printer.MacAddress,
                    IsInRange = true
                });
            }
        } 

    printersList = nearbyDevicesInDB;

    printersList.Add(new Models.Printer
    {
        SerialNumber = "--",
        MacAddress = "--"
    });

    printersList.AddRange(printers);

    return printersList;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.