C# - Merging List of Objects into One Object

c#

Solution

So I am looking to eliminate the assumption that they are in the correct order

Something like this perhaps?:

Aa = smalls.Single(s => s.Name == "Aa").Value

This at least still relies on the assumption that the record will be there at all, though it doesn't care about the order of the records. If you want to drop that assumption as well, you can add some error checking. Something like this perhaps:

Aa = smalls.Any(s => s.Name == "Aa") ? smalls.First(s => s.Name == "Aa") : string.Empty

It's not the most efficient thing in the world, but at least remains on one line as in your current usage. Separating into multiple lines will make it longer, but potentially more performant (if performance is even an issue... in the very small example provided it really isn't).

Those multiple lines could potentially then be re-factored into a custom extension method to put it back onto a single line? The sky's the limit, really.

Problem

I get passed a list of small objects: ``` var smalls = new List<Small>(); smalls.AddRange( new Small[] { new Small{Name = "Aa", Id = 1, Value = "v1"}, new Small{Name = "Bb", Id = 1, Value = "v2"}, new Small{Name = "Cc", Id = 1, Value = "v3"}, new Small{Name = "Dd", Id = 1, Value = "v4"}, new Small{Name = "Ee", Id = 1, Value = "v5"}, new Small{Name = "Ff", Id = 1, Value = "v6"}, new Small{Name = "Gg", Id = 1, Value = "v7"} } ); ``` From the above list I would like to populate an object that looks like this: ``` var large = new Large { Id = 1, Aa = "v1", Bb = "v2", Cc = "v3", Dd = "v4", Ee = "v5", Ff = "v6", Gg = "v7" } ``` The current code relies on the order of the list to populate the Large object however this does not feel secure enough and am looking for a more reliable way to map the list into the object. Current code: ``` Large large = new Large { Id = smalls[0].Id, Aa = smalls[0].Value, Bb = smalls[1].Value, Cc = smalls[2].Value, Dd = smalls[3].Value, Ee = smalls[4].Value, Ff = smalls[5].Value, Gg = smalls[6].Value } ``` So I am looking to eliminate the assumption that they are in the correct order and populate the new fields based off of the Name string in the Small object into the corresponding field in the Large object. Thanks for any input!!

Original source