Coolest C# LINQ/Lambdas trick you've ever pulled?

后端 未结 14 1452
死守一世寂寞
死守一世寂寞 2020-12-22 17:00

Saw a post about hidden features in C# but not a lot of people have written linq/lambdas example so... I wonder...

What\'s the coolest (as in the most

14条回答
  •  半阙折子戏
    2020-12-22 18:04

    Working with attributes:

    private void WriteMemberDescriptions(Type type)
    {
        var descriptions =
            from member in type.GetMembers()
            let attributes = member.GetAttributes(true)
            let attribute = attributes.FirstOrDefault()
            where attribute != null
            select new
            {
                Member = member.Name,
                Text = attribute.Description
            };
    
            foreach(var description in descriptions)
            {
                Console.WriteLine("{0}: {1}", description.Member, description.Text);
            }
    }
    

    The GetAttributes extension method:

    public static class AttributeSelection
    {
        public static IEnumerable GetAttributes(this ICustomAttributeProvider provider, bool inherit) where T : Attribute
        {
            if(provider == null)
            {
                throw new ArgumentNullException("provider");
            }
    
            return provider.GetCustomAttributes(typeof(T), inherit).Cast();
        }
    }
    

    AttributeSelection is production code and also defines GetAttribute and HasAttribute. I chose to use the let and where clauses in this example.

提交回复
热议问题