开发者

Removing properties from PropertyInfo[]

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[] GetAllP开发者_运维知识库ropertyForClass(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


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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜