Last post Mar 17, 2015 08:55 PM by Paul Linton
Mar 16, 2015 09:24 AM|CsharpAsp.net|LINK
I am using this below code to get all the custom attribute decorated on my method as:
MethodInfo method = typeof(Core).GetMethod("MyMethod");
CustomAttribute attr = (CustomAttribute)method.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute ar in attr)
Above is an arraylist and I dont want to use arrray list.
So bascially I want to get all the values from my custom attribute and pass that to another function.
Mar 16, 2015 09:31 AM|AidyF|LINK
I don't really understand the question. An array is probably the most efficient list structure there is, and to convert it to something else will make it *less* efficient. What you convert it to depends on what the function accepts. Other than an array
you can use a List;
var x = attr.ToList();
Beyond that you'll need to explain your requirements a bit more.
Mar 16, 2015 09:51 AM|Rion Williams|LINK
Since the GetCustomAttributes() method is already returning an array of objects, you'll probably be hard pressed to find a more efficient list-like data structure (especially with the use of LINQ if you need to perform any type of filtering) after casting
it to the appropriate type.
Are you simply trying to access a specific property from each of the values in your collection? If so, you might could use something like this :
// Get the Value property of each of your Custom Attributes and store it in an array
var values = attr.Select(a => a.Value).ToArray();
Could you provide a bit more specifics for exactly what you are after?
Mar 17, 2015 08:55 PM|Paul Linton|LINK
You don't say how you choose the custom attributes that you want (is it a property of the attribute or do you pass the attribute to a method returning bool or is it something to do with the name of the attribute or does the attribute inherit from a known
parent or ...)
You don't say what data structure you want as a result (List, Dictionary, Queue, your own creation ...)
But ... the body of the foreach will be something like
if (attributeOfInterest(ar)) collectionListTypeThingo.AddOrInsertorWhateverIsSupported(ar);
You will need to create an instance of the data structure that you desire (called collectionListTypeThingo in my sample) before the foreach starts.