Let's start by defining a class for an example:
public class Person { public string FirstName; public string LastName; public int Age; public int Grade; }
Now suppose I have a List<Person> called people containing 3 objects:
{"Robby", "Goki", 12, 8} {"Bobby", "Goki", 10, 8} {"Sobby", "Goki", 10, 8}
What I'm looking for is a way to get the following single Person object:
{null, "Goki", -1, 8}
where fields that are the same in all objects retain their value, and fields that have several values are replaced by some invalid value.
My first thought consisted of:
Person unionMan = new Person(); if (people.Select(p => p.FirstName).Distinct().Count() == 1) unionMan.FirstName = people[0].FirstName; if (people.Select(p => p.LastName).Distinct().Count() == 1) unionMan.LastName = people[0].LastName; if (people.Select(p => p.Age).Distinct().Count() == 1) unionMan.Age = people[0].Age; if (people.Select(p => p.Grade).Distinct().Count() == 1) unionMan.Grade = people[0].Grade;
Unfortunately, a real business object has many more members than four, and it is tiring to write and suppress, so that someone else can see for the first time.
I also thought about how to use reflection to put these repeating checks and assignments in a loop:
string[] members = new string[] { "FirstName", "LastName", "Age", "Grade" }; foreach (string member in members) { if (people.Select(p => p.**member**).Distinct().Count() == 1) unionMan.**member** = people[0].**member**; }
where ** member ** will be, however, reflection will allow you to get and save this particular element (if possible).
While the first solution will work, and the second that I assume will work, does anyone have a better alternative solution to this problem? If not, is reflection possible as described above possible?