Finding empty fields in an object - C #

We have a scenario in which, if an entity exists between the source and the target, we must combine the data into the target, that is, copy the values ​​from the columns of the fund, where the target column is empty.

We use WCF service calls, and we have entity objects.

If I have an entity, say Staff , the staff encodes the basic properties for the name, etc., and we have a list for StaffAddress , StaffEmail and StaffPhone .

So, I just wanted to find out if there is a way to use LINQ or some other mechanism - can I find out a list of the properties of the Staff object that are empty or empty?

One rudimentary way is, of course, manually checking one property for an empty one?

+4
source share
3 answers

Here's a quick and dirty way to do it with LINQ

 public static IEnumerable<string> FindBlankFields(Staff staff) { return staff.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(p => p.CanRead) .Select(p => new { Property = p, Value = p.GetValue(staff, null) }) .Where(a => a.Value == null || String.IsNullOrEmpty(a.Value.ToString())) .Select(a => a.Property.Name); } 
+1
source

You can get all properties by reflection, and then call GetValue for each instance of PropertyInfo. If it is zero, you will return PropertyInfo:

 static IEnumerable<PropertyInfo> GetNullProperties(object obj) { // Get the properties and return only the ones where GetValue // does not return null. return from pi in obj.GetType().GetProperties( BindingFlags.Instance | BindingFlags.Public) where pi.GetValue(obj, null) != null select pi; } 

Remember that this will return only public properties of the type, and not public properties.

+5
source

You will need to use some reflection for this:

 var unsetProperties = from prop in foo.GetType().GetProperties() let value = prop.GetValue(foo, null) where value == null || value.Equals(string.Empty) select prop.Name; 
0
source

All Articles