Hier wollen wir zwei Array vergleichen, um die fehlende Array-Elemente herauszufinden. Beide Arrays sind vom Typ “Element” .
public class Element { public int DeviceKey { get; set; } public int SwitchKey { get; set; } }
Das Array “fullElements” beinhaltet alle Kombinationen. Das “incompleteElements” hat nur einen Teil davon.
public static void Main(string[] args) { var fullElements = new List<Element>(); var incompleteElements = new List<Element>(); // (Device = 1) Beide Arrays haben die gleichen Pärchen fullElements.Add(new Element{ DeviceKey = 1, SwitchKey = 1}); incompleteElements.Add(new Element { DeviceKey = 1, SwitchKey = 1 }); fullElements.Add(new Element { DeviceKey = 1, SwitchKey = 2 }); incompleteElements.Add(new Element { DeviceKey = 1, SwitchKey = 2 }); fullElements.Add(new Element { DeviceKey = 1, SwitchKey = 3 }); incompleteElements.Add(new Element { DeviceKey = 1, SwitchKey = 3 }); // (Device = 2) Nur ein Array hat elemente fullElements.Add(new Element { DeviceKey = 2, SwitchKey = 1 }); fullElements.Add(new Element { DeviceKey = 2, SwitchKey = 9 }); fullElements.Add(new Element { DeviceKey = 2, SwitchKey = 3 }); // (Device = 3) Die Arrays haben gemischte Elemente fullElements.Add(new Element { DeviceKey = 3, SwitchKey = 1 }); incompleteElements.Add(new Element { DeviceKey = 3, SwitchKey = 1 }); fullElements.Add(new Element { DeviceKey = 3, SwitchKey = 2 }); fullElements.Add(new Element { DeviceKey = 3, SwitchKey = 22 }); incompleteElements.Add(new Element { DeviceKey = 3, SwitchKey = -1 }); fullElements.Add(new Element { DeviceKey = 3, SwitchKey = 33 }); incompleteElements.Add(new Element { DeviceKey = 3, SwitchKey = 33 }); // TODO ... Console.ReadKey(); }
Hier zwei Möglichkeiten, um die fehlende Elemente zu finden:
Lösung 1)
// Solution 1) foreach (var fullElement in fullElements) { // Device found if (!incompleteElements.Any(incomplete => incomplete.DeviceKey.Equals(fullElement.DeviceKey) && incomplete.SwitchKey.Equals(fullElement.SwitchKey)) ) { Log("Device/Switch not found"); } }
Lösung 2)
// Solution 2) var notMappedElements = fullElements.FindAll(fullElement => !incompleteElements.Any(incomplete => incomplete.DeviceKey.Equals(fullElement.DeviceKey) && incomplete.SwitchKey.Equals(fullElement.SwitchKey)));