2009-02-06 54 views
4

我們有一個場景,其中如果實例存在於源和目標之間,我們應該合併目標中的數據,即從目標列爲空的基礎列複製值。查找對象中的空白字段 - C#

我們正在使用WCF服務調用,並且我們有實體對象。

如果我有一個實體可以說Staff,工作人員conatins的姓名等基本屬性,我們有StaffAddressStaffEmailStaffPhone列表。

所以我只是想知道是否有一種方法使用LINQ或任何其他機制 - 我可以找到Staff對象的屬性列表爲空或空白?

一個基本的方法當然是手動檢查一個空白的屬性?

回答

1

這裏有一個快速和骯髒的方式與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); 
} 
5

您可以通過反射獲取所有屬性,然後在每個PropertyInfo實例上調用GetValue。凡爲空,你將返回的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; 
} 

你要知道,這將在類型,而不是非公共屬性僅返回公共屬性。

+0

另外,我不相信這會告訴你,如果一個字符串是空的。但是,這可以很容易地修改來做到這一點。 – BobbyShaftoe 2009-02-06 22:30:55

+0

美麗,我愛酷LINQ +1 – bendewey 2009-02-06 22:32:48

0

您將需要使用一些這方面的反思:

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