tags:

views:

59

answers:

2

So I have two "documents" that both have allot of properties. One document is an instance of a document that has been filled out. I need to check if there is a 'Value" in the property (since they are mainly nullable int?) and if so assign the value of the current property to the property of the other document.

Example

if (documentA.FirstProperty.HasValue)
{
    documentB.FirstProperty = documentA.FirstProperty
}

But is there a way to make this clearner? I thought maybe I could create a list of the document type and using a foreach loop and check if the current property has a value and if so assign it to the new document.

With having already acquired an instance of a document called oldDocument

Example:

List<oldDocument> listOfProperties = new List<oldDocument>();

foreach (var property in listOfProperties)
{
    if (property.HasValue)
    {
        documentB.property = documentA.property;
    }
}

Where the variable "property" in the foreach loop would represent the name of the property?

+3  A: 

You can use linq for that.

var nullProps = doc1.SelectMany(d => d.Props).Where(prop => prop == null); 
//Assign
foreach(var prop in nullProps)
     doc1.Prop[prop.Name] = doc2.Prop[prop.Name];
schoetbi
It appears your LINQ sugestion requires the properties in a list But if the instance of the document is just a bunch of automatic properties, how do I load them in a list?
pghtech
For Linq only the interface IEnumerable<T> is required. So the best thing I could think of create a temporary Enumerable (i.e. a list) and add all properties into it. You could create it with a method on the document like this: List<Property> lst = doc.GetPropertiesAsList();That way you can use LINQ for this problem.
schoetbi
+3  A: 

Null coalesce could at least simplify the assignment blocks:

DocumentA.FirstProperty = DocumentB.FirstProperty ?? DocumentA.FirstProperty;
Peter Leppert