Last active
February 10, 2019 17:01
-
-
Save VitalyKondratiev/dff142987f71cc69328b021b0fa9d6f8 to your computer and use it in GitHub Desktop.
Get object by value of selected property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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