Reputation: 1837
What is the simplest way of removing first four properties from 'properties'. Where properties is PropertyInfo collection as shown below.
PropertyInfo[] properties = GetAllPropertyForClass(className);
public static PropertyInfo[] GetAllPropertyForClass(string className) {
Type[] _Type = Assembly.GetAssembly(typeof(MyAdapter)).GetTypes();
return _Type.SingleOrDefault(
t => t.Name == className).GetProperties(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
}
Of course I can loop through and build one more PropertyInfo[] collection by ignoring property based on its index or name. But I want to know if there is any way to achieve without looping through the properties.
Thanks
Upvotes: 1
Views: 4722
Reputation: 172380
LINQ helps:
PropertyInfo[] almostAllProperties = properties.Skip(4).ToArray();
This works for all kinds of IEnumerables, not only arrays of PropertyInfo.
EDIT: As others have pointed out, excluding properties by name is more robust. Here's how you'd do that with LINQ:
PropertyInfo[] almostAllProperties = properties.Where(
p => p.Name != "ExcludeProperty1"
&& p.Name != "ExcludeProperty2"
&& p.Name != "ExcludeProperty3").ToArray();
Upvotes: 7
Reputation: 54377
PropertyInfo[] filteredProperties = new PropertyInfo[properties.Length - 4];
for( int i = 4, x = 0; i < properties.Length; i++, x++ )
{
filteredProperties[x] = properties[i];
}
This is probably the cheapest way in terms of clock cycles, although nothing fancy.
Unless this is just test code, you should never count on the first four properties being the same. Reflection doesn't guarantee sequence.
Upvotes: 1