Coolest C# LINQ/Lambdas trick you've ever pull

2019-01-29 16:32发布

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 elegant) use of the C# LINQ and/or Lambdas/anonymous delegates you have ever saw/written?

Bonus if it has went into production too!

14条回答
\"骚年 ilove
2楼-- · 2019-01-29 17:05

I think that LINQ is a major change to .NET and it is a very powerful tool.

I use LINQ to XML in production to parse and filter records from a 6MB XML file (with 20+ node levels) into a dataset in two lines of code.

Before LINQ this would have taken hundreds of lines of code and days to debug.

That's what I call elegant!

查看更多
Deceive 欺骗
3楼-- · 2019-01-29 17:07

Working with attributes:

private void WriteMemberDescriptions(Type type)
{
    var descriptions =
        from member in type.GetMembers()
        let attributes = member.GetAttributes<DescriptionAttribute>(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<T> GetAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute
    {
        if(provider == null)
        {
            throw new ArgumentNullException("provider");
        }

        return provider.GetCustomAttributes(typeof(T), inherit).Cast<T>();
    }
}

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

查看更多
登录 后发表回答