I have a list of Tuples with generic objects (List<Tuple<T?, T?>>). I am able to sort based on two properties from the objects in either the first or second element without an issue. The problem is that either the first or second element's object could be null. What I need to be able to do is sort on the first item by the two properties, but if the first item is null, then use the second item's same two properties. When I try to do this using a ternary operator it errors on the null item even after a null check.
More details:
The list contains comparison items.
The first item in the Tuple is the source item, the second is the target of the comparison.
If the source item does not have a match in the target, the second element in the tuple will be null.
If the target item does not have a match in the source, the first element in the tuple will be null.
The sort is done on two properties of each object which make them unique to the environment they are in.
Example: A list of products which has a category and name where the combination of those two items is unique.
I need the sort to put the items in each category together for readability. So if there is a category "Tools" with a product named "Hammer" which exists in the second element of the tuple, but has no match in the first (so it is null) it will be listed in order with the other category items of "Tools" from the first element. Not at the end by itself.
What I thought would work is the below, but it breaks if there is a null even with the null check. What can I do to get this to work?
I am also open to better ways of doing this if someone has a better idea.
List<Tuple<T?, T?>> allItems = comparisonList
.OrderBy(x => x.Item1.GetType().GetProperty(sortPropA) is null ? x.Item2.GetType().GetProperty(sortPropA).GetValue(x.Item2) : x.Item1.GetType().GetProperty(sortPropA).GetValue(x.Item1))
.ThenBy(x => x.Item1.GetType().GetProperty(sortPropB) is null ? x.Item2.GetType().GetProperty(sortPropB).GetValue(x.Item2) : x.Item1.GetType().GetProperty(sortPropB).GetValue(x.Item1))
.ToList();