'Find class method by value
How to make a search method for a class object that finds a property that contains the searched value?
I now the class property has string value - "Anna", but I need to know what property holds it.
Tell if need more information.
class Program
{
public static void Main(string[] args)
{
First first = new First()
{
Name = "Anna",
Nick = "Alise"
};
string find = "Anna";
string some = first.Equals_SomeMethodWith(find);// How to do this?
Console.WriteLine(some);
}
}
class First
{
public string Name { get; set; }
public string Nick { get; set; }
}
Solution 1:[1]
Assuming you mean properties, not methods, then something like:
var props = first.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in props)
{
if (prop.PropertyType == typeof(string))
{
try
{
if (prop.GetValue(first) is string val && val == find)
{
Console.WriteLine($"{prop.Name}={val}");
}
}
catch { } // best efforts
}
}
Or for an array (comments):
First[] objects = new[] {
new First()
{
Name = "Fred",
Nick = "Freddy"
},
new First()
{
Name = "Anna",
Nick = "Alise"
},
new First()
{
Name = "Robert",
Nick = "Bob"
},
};
string find = "Anna";
var index = Array.FindIndex(objects, x => AnyPropEquals(x, find));
Console.WriteLine(index);
static bool AnyPropEquals<T>(object obj, T value)
{
var props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in props)
{
if (prop.PropertyType == typeof(T))
{
try
{
if (prop.GetValue(obj) is T val && EqualityComparer<T>.Default.Equals(val, value))
return true;
}
catch { } // best efforts
}
}
return false;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
