I have a requirement to create an object 'factory' that works as follows:
- Accepts a list of matching object types.
- Compares each property value in the list to see if they match.
- Returns a new single instance of that object type, with just the matching fields set.
(For simplicity, we can assume all propeties are strings)
For example, from this list of person objects:
Person1 { Name: "Bob", Job: "Policeman", Location: "London" }
Person2 { Name: "John", Job: "Dentist", Location: "Florida" }
Person3 { Name: "Mike", Job: "Dentist", Location: "London" }
Person4 { Name: "Fred", Job: "Doctor", Location: "London" }
If I passed in a list containing person 2 & 3 it would return a new person like so:
Name: "No Match", Job: "Dentist", Location "No Match"
If I passed in person 3 & 4 it would return a new person:
Name: "No Match", Job: "No Match", Location "London"
So far....
Using the answer from this SO question
:
How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?
I can get this LINQ to work for a single known object, but I need it to be generic.
This covers just one specific property but my objects have 30+ properties.
var otherValue="No Match"
var matchingVal= people.First().Job;
return people.All(x=>x.Job== matchingVal) ? matchingVal: otherValue;
I am also aware I can use reflection to get a list of properties in my object. But how to combine all of that into a single 'factory' is beyond by comprehension.
I don't think this is a unique problem but I cannot find a complete solution in any of my searching. Maybe there is already a Nuget package out there that can help me?
All advice gratefully received.