2017-08-24 113 views
0

我有UserInformation檢查是否有對象屬性包含字符串

List<UserInformation> ui = new List<UserInformation>(); 

的UserInformation物體看起來像這樣的列表;

public class UserInformation 
{ 
    public UserInformation() 
    { 
    } 

    public UserInformation(UserInformation u) 
    { 
     this.Id = u.Id; 
     this.parentId = u.parentId; 
     this.Name = u.Name; 
     this.Title = u.Title; 
     this.Department = u.Department; 
     this.Image = u.Image; 
     this.Parent = u.Parent; 
     this.Username = u.Username; 
     this.Company = u.Company; 
     this.Initials = u.Initials; 
     this.Disabled = u.Disabled; 
    } 

    public int Id { get; set; } 
    public int? parentId { get; set; } 
    public string Name { get; set; } 
    public string Title { get; set; } 
    public string Department { get; set; } 
    public string Image { get; set; } 
    public string Parent { get; set; } 
    public string Username { get; set; } 
    public string Company { get; set; } 
    public string Initials { get; set; } 
    public bool Disabled { get; set; } 
} 

是否有某種方法來檢查這些屬性中是否包含特定的Word?可以說「.test」?

更新

我還挺想避免類似

!new[] { ".ext", ".test", ".admin" }.Any(c => ui.Title.ToLower().Contains(c)) 
!new[] { ".ext", ".test", ".admin" }.Any(c => ui.Department.ToLower().Contains(c)) 
!new[] { ".ext", ".test", ".admin" }.Any(c => ui.Company.ToLower().Contains(c)) 
!new[] { ".ext", ".test", ".admin" }.Any(c => ui.Username.ToLower().Contains(c)) 
+0

'OBJ。屬性==「.test」'??? – Rahul

+0

我認爲他的意思是像反射,獲取屬性和比較那些字符串類型爲「.test」。對? –

+0

我想檢查整個'UserInformation'對象是否包含「.test」,它可以是任何包含單詞 –

回答

1

您可以使用此方法使用反射來獲取包含文本的所有屬性:

public static IEnumerable<PropertyInfo> PropertiesThatContainText<T>(T obj, string text, StringComparison comparison = StringComparison.Ordinal) 
{ 
    var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance) 
     .Where(p => p.PropertyType == typeof(string) && p.CanRead); 
    foreach (PropertyInfo prop in properties) 
    { 
     string propVal = (string)prop.GetValue(obj, null); 
     if (String.Equals(text, propVal, comparison)) yield return prop; 
    } 
} 

如果您只是想知道是否至少有一個屬性:

bool anyPropertyContainsText = PropertiesThatContainText(yourUserInfo, ".test").Any(); 

但總的來說,我會盡可能避免使用反射。相反,請在UserInformation中創建一個明確檢查相關屬性的方法。或者只是檢查一下你必須知道的地方。有點冗長但可讀,每個人都會理解你的代碼,包括你自己。

0

您可以像DavidG指出的那樣使用運行時反射;

How to iterate all "public string" properties in a .net class

但如果你這樣做了大的數據集(即所有用戶),這將是緩慢的 - 在這種情況下,更好的辦法是使用T4模板來生成代碼;

https://msdn.microsoft.com/en-us/library/bb126445.aspx

,或者在任何一個數據庫執行此(如果其中的信息來自這就是),或者創建索引,並使用「搜索」引擎像Lucene的

https://lucene.apache.org/

相關問題