patterncsharpMinor
Handling newly devices added to or removed from a list
Viewed 0 times
handlingremovedaddeddeviceslistfromnewly
Problem
I have two lists that I need to intersect. This is what I'm doing.
I need to react accordingly to each item that is either removed or added. Is there any way to reduce this code?
var dfuDevices = _dfuMonitor.GetDevices();
// new devices
dfuDevices.Except(Devices).AsParallel().ForAll(device => {
if (device.GetType() == typeof(DFUDeviceModel)) {
OnDfuDeviceDetected(device);
}
});
// removed devices
Devices.Except(dfuDevices).AsParallel().ForAll(device => {
if (device.Equals(ConnectedDevice))
Disconnect();
if (device is DFUDeviceModel)
OnDfuDeviceRemoved(device);
});
// refresh list
Devices = Devices.Intersect(dfuDevices);I need to react accordingly to each item that is either removed or added. Is there any way to reduce this code?
Solution
Detecting changes
What you need is an ObservableCollection:
Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Your code is very short so there is not much to comment on but there is one more thing that you can improve.
You can simplify this by using the
Filters the elements of an IEnumerable based on a specified type.
What you need is an ObservableCollection:
Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Your code is very short so there is not much to comment on but there is one more thing that you can improve.
dfuDevices.Except(Devices).AsParallel().ForAll(device => {
if (device.GetType() == typeof(DFUDeviceModel)) {
OnDfuDeviceDetected(device);
}
});You can simplify this by using the
OfType() extension thatFilters the elements of an IEnumerable based on a specified type.
dfuDevices
.Except(Devices)
.OfType()
.AsParallel()
.ForAll(OnDfuDeviceDetected);Code Snippets
dfuDevices.Except(Devices).AsParallel().ForAll(device => {
if (device.GetType() == typeof(DFUDeviceModel)) {
OnDfuDeviceDetected(device);
}
});dfuDevices
.Except(Devices)
.OfType<DFUDeviceModel>()
.AsParallel()
.ForAll(OnDfuDeviceDetected);Context
StackExchange Code Review Q#138274, answer score: 5
Revisions (0)
No revisions yet.