Enumerating through an object's properties (string) in C#
Use reflection. It's nowhere near as fast as hardcoded property access, but it does what you want.
The following query generates an anonymous type with Name and Value properties for each string-typed property in the object 'myObject':
var stringPropertyNamesAndValues = myObject.GetType()
.GetProperties()
.Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
.Select(pi => new
{
Name = pi.Name,
Value = pi.GetGetMethod().Invoke(myObject, null)
});
Usage:
foreach (var pair in stringPropertyNamesAndValues)
{
Console.WriteLine("Name: {0}", pair.Name);
Console.WriteLine("Value: {0}", pair.Value);
}
Loop through an object's properties and get the values for those of type DateTime
You need to use car
as the first parameter:
foreach (var car in carList)
{
foreach (PropertyInfo prop in car.GetType().GetProperties())
{
var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
if (type == typeof (DateTime))
{
Console.WriteLine(prop.GetValue(car, null).ToString());
}
}
}
iterate through object properties of type string c#
bool IsPersonInvalid(Person person)
{
bool HasSpecialCharacter(string value)
{
// Replace with something more useful.
return value?.Contains("$") == true;
}
return typeof(Person)
// Get all the public Person properties
.GetProperties()
// Only the ones of type string.
.Where(x => x.PropertyType == typeof(string))
// Get the values of all the properties
.Select(x => x.GetValue(person) as string)
// Check any have special chars
.Any(HasSpecialCharacter);
}
var person1 = new Person
{
FirstName = "Bob$Bob",
LastName = "Fred"
};
Console.WriteLine(IsPersonInvalid(person1)); // True
var person2 = new Person
{
FirstName = "Bob",
LastName = "Fred"
};
Console.WriteLine(IsPersonInvalid(person2)); // False
Iterating through Object Properties in C#
public IEnumerator<PropertyInfo> GetEnumerator()
{
return GetEnumerator();
}
This method is calling itself, eventually your stack will overflow. Implement it properly:
public IEnumerator<PropertyInfo> GetEnumerator()
{
foreach (var property in typeof(Customer).GetProperties())
{
yield return property;
}
}
How to iterate through all string properties and change their values using System.Reflection
Once you have found a property you can write:
string value = (string)propInfo.GetValue(this);
// manipulate
propInfo.SetValue(this, value);
Hence the method can be:
public void Sanitize()
{
var CheckItemType = typeof(SpecialClass);
var strType = typeof(string);
var propInfos = CheckItemType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach ( var propInfo in propInfos )
if ( propInfo.PropertyType == strType && propInfo.CanWrite )
{
string value = (string)propInfo.GetValue(this);
// manipulate
propInfo.SetValue(this, value);
}
}
You can also use Linq:
public void Sanitize()
{
var typeString = typeof(string);
var propertiesInfos = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeString
&& p.CanWrite
&& p.CanRead);
foreach ( var propertyInfo in propertiesInfos )
{
string value = (string)propertyInfo.GetValue(this);
// manipulate
propertyInfo.SetValue(this, value);
}
}
Here we parse instance (this) properties, not static... so you can see the @DmitryBychenko answer to consider them and use null
instead of this
on static member by adding BindingFlags.Static
to select them if needed.
Iterating through object properties and setting nullable properties through user input
Use Nullable.GetUnderlyingType()
to get the underlying type of a nullable type. If it's not a nullable type, it returns null
, so you can check for null
and use the actual property type instead. Like this:
var convertedInput = Convert.ChangeType(input,
Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
loop through object and get properties
You can do it with reflection:
// Obtain a list of properties of string type
var stringProps = OS_Result
.OSResultStruct
.GetType()
.GetProperties()
.Where(p => p.PropertyType == typeof(string));
foreach (var prop in stringProps) {
// Use the PropertyInfo object to extract the corresponding value
// from the OS_Result.OSResultStruct object
string val = (string)prop.GetValue(OS_Result.OSResultStruct);
...
}
[EDIT by Matthew Watson]
I've taken the liberty of adding a further code sample, based on the code above.
You could generalise the solution by writing a method that will return an IEnumerable<string>
for any object type:
public static IEnumerable<KeyValuePair<string,string>> StringProperties(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(string)
select new KeyValuePair<string,string>(p.Name, (string)p.GetValue(obj));
}
And you can generalise it even further with generics:
public static IEnumerable<KeyValuePair<string,T>> PropertiesOfType<T>(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(T)
select new KeyValuePair<string,T>(p.Name, (T)p.GetValue(obj));
}
Using this second form, to iterate over all the string properties of an object you could do:
foreach (var property in PropertiesOfType<string>(myObject)) {
var name = property.Key;
var val = property.Value;
...
}
Iterate object list and get element property with a string
You could use reflection to get the value of a property by name:
foreach (Person p in persons)
{
var personId = typeof(Person).GetProperty("ID").GetValue(p, null) as string;
}
Of course this needs some error handling and some null
checks, but you get the gist :)
Iterate through list objects to find object with matching property value
You can use LINQ
:
public User GetUser(string name)
{
return users.FirstOrDefault(x => x.GetName().Equals(name));
}
Note: if such a name does not exist, the default will be returned, the default for this case isnull
.
Related Topics
Generate 16-Bit Grayscale Bitmapdata and Save to File
Jquery Ajax Call to an ASP.NET Webmethod
How to Write the Escape Char '\' to Code
Does C# Support Project-Wide Default Namespace Imports Like Vb.Net
Datagridview Using Sortablebindinglist
Finding a Subsequence in Longer Sequence
Caliburn.Micro Serialization Issue When Implementing Propertychangedbase
Is This Thread.Abort() Normal and Safe
How to Quickly Up-Cast Object[,] into Double[,]
C# Arrow Key Input for a Console App
Strange Behaviour of Console.Readkey() with Multithreading
Converting ASP.NET MVC Razor @Helper Function into a Method of a Helper Class
Generic C# Code and the Plus Operator
Parent Control Mouse Enter/Leave Events with Child Controls