abe
abe

Reputation: 4136

how to update an object using linq?

I have userObject which has about 30 properties.

I get a updated userObject from the server and only sets the properties of the ones that have changed and returns the rest as null.

i am currently using a foreach and chk the value from the server is not null then update it. Is there a way to just to update the cells that are not null using linq?

linq to object

public class UserProfile
   {
        public string string00 { get; set; }
        public string string01 { get; set; }
        public string string02 { get; set; }
        public string string03 { get; set; }
        public string string04 { get; set; }

        public boolean bool00 { get; set; }
        public boolean bool01 { get; set; }
        public boolean bool02 { get; set; }
        public boolean bool03 { get; set; }
        public boolean bool04 { get; set; }
   }

Upvotes: 1

Views: 441

Answers (1)

hyp
hyp

Reputation: 1380

You can use Reflection.

class Program
{
    static void Main(string[] args)
    {
        myClass currentObj = new myClass() { Text = "test", Value = 5 };
        myClass updatedObj = new myClass() { Text = "test 2 ", Value = 6 };
        Type cType = currentObj.GetType();
        var fieldInfos = cType.GetFields();

        foreach (var fieldInfo in fieldInfos)
        {
            if (fieldInfo.GetValue(updatedObj) != null)
            {
                fieldInfo.SetValue(currentObj, fieldInfo.GetValue(updatedObj));
            }
        }
    }
}

class myClass
{
    public string Text;
    public int Value;
}

Just Template the code and change it into a function. Some more info: here

Upvotes: 2

Related Questions