Unique Property Attribute value per class
Here is my Attribute class:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TagAttribute : Attribute
{
public TagAttribute (string tag)
{
Tag = tag;
}
public string Tag { get; set; }
}
The idea is that you create a class and decorate each property with the tag attribute and the tag value. For example: the property Name would have the attribute Tag("UserId")
One of the validations i need to check is that the tag value ("UserId") is unique per class properties. Meaning no other property has a tag with the same value ("UserId")
开发者_如何学编程I'm pretty sure there is a simple way to do this with LINQ but casting must done too and i'd appreciate some help :)
Thanks in advance :)
This code will print all duplicate tags in a given assembly, and the list of properties that have this tag:
Assembly asm = ...
var propertiesByTag =
from t in asm.GetTypes()
from p in t.GetProperties()
from a in p.GetCustomAttributes(typeof(TagAttribute)).Cast<TagAttribute>()
group p by a.Tag into g
select new
{
Tag = g.Key,
Properties = g.ToArray()
}
foreach (var dup in propertiesByTag.Where(x => x.Properties.Length > 1))
{
Console.WriteLine("Duplicated tag: {0}", dup.Tag);
foreach(var p in dup.Properties)
Console.WriteLine("\t{0}.{1}", p.DeclaringType.Name, p.Name);
}
精彩评论