Peter Hansen Peter Hansen - 30 days ago 12
C# Question

Check if any object property contains string

I have a list of


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

The UserInformation object looks like this;

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; }

Is there some way to check if any of these properties, contains a specific Word? Lets say ".test"?


I kinda want to avoid something like

!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))

Answer Source

You could use this method using reflection to get all properties that contain your text:

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;

If you just want to know if there was at least one property:

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

But in general i would avoid using reflection wherever possible. Instead create a method in UserInformation that checks the relevant properties explicitly. Or just check it where you have to know it. A little verbose but readable and everyone will understand your code including yourself.