Skip to content

Instantly share code, notes, and snippets.

@VitalyKondratiev
Last active February 10, 2019 17:01
Show Gist options
  • Save VitalyKondratiev/dff142987f71cc69328b021b0fa9d6f8 to your computer and use it in GitHub Desktop.
Save VitalyKondratiev/dff142987f71cc69328b021b0fa9d6f8 to your computer and use it in GitHub Desktop.
Get object by value of selected property
object GetObjectByName<T>(string needle, T[] objs, string propertyName = "")
{
foreach (T obj in objs)
{
/*
* For string objects uses string value
* For another objects property searched by given string
* If property not found, uses obj.ToString() value
*/
string searched_value;
if (typeof(string).Equals(obj.GetType()))
{
searched_value = obj.ToString();
}
else
{
var apropriate_property = obj.GetType().GetProperties().FirstOrDefault(c => c.Name.Equals(propertyName));
searched_value = (apropriate_property != null) ? apropriate_property.GetValue(obj).ToString() : obj.ToString();
}
if (searched_value == needle)
return obj;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment