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条回答
疯言疯语
2楼-- · 2019-01-29 16:43

To me, the duality between delegates (Func<T,R>, Action<T>) and expressions (Expression<Func<T,R>> Expression<Action<T>>) is what gives rise to the most clever uses of lambdas.

For example:

public static class PropertyChangedExtensions
{
    public static void Raise(this PropertyChangedEventHandler handler, Expression<Func<object>> propertyExpression)
    {
        if (handler != null)
        {
            // Retrieve lambda body
            var body = propertyExpression.Body as MemberExpression;
            if (body == null)
                throw new ArgumentException("'propertyExpression' should be a member expression");

            // Extract the right part (after "=>")
            var vmExpression = body.Expression as ConstantExpression;
            if (vmExpression == null)
                throw new ArgumentException("'propertyExpression' body should be a constant expression");

            // Create a reference to the calling object to pass it as the sender
            LambdaExpression vmlambda = Expression.Lambda(vmExpression);
            Delegate vmFunc = vmlambda.Compile();
            object vm = vmFunc.DynamicInvoke();

            // Extract the name of the property to raise a change on
            string propertyName = body.Member.Name;
            var e = new PropertyChangedEventArgs(propertyName);
            handler(vm, e);
        }
    }
}

Then you can "safely" implement INotifyPropertyChanged by calling

if (PropertyChanged != null)
    PropertyChanged.Raise( () => MyProperty );

Note : I saw this on the web at first a few weeks ago, then lost the link and a score of variations have cropped up here and there since then so I'm afraid I cannot give proper attribution.

查看更多
不美不萌又怎样
3楼-- · 2019-01-29 16:44

OLINQ reactive LINQ queries over INotifyingCollection - these allow you to do (amongst other things) realtime aggregation against large datasets.

https://github.com/wasabii/OLinq

查看更多
叼着烟拽天下
4楼-- · 2019-01-29 16:50

Not my design but I've used it a few times, a typed-switch statement: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx

Saved me so many if... else if... else if... else IF! statements

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-29 16:51

I was trying to come up with a cool way to build a navigation control for a website I was building. I wanted to use regular HTML unordered list elements (employing the standard CSS "Sucker Fish" look) with a top-navigation mouse-over effect that reveals the drop down items. I had a sql dependent cached DataSet with two tables (NavigationTopLevels & NavigationBottomLevels). Then all I had to was create two class objects (TopNav & SubNav) with the few required properties (the TopNav class had to have a generic list of bottomnav items -> List<SubNav> SubItems).


var TopNavs = from n in ds.NavigationTopLevels select new TopNav { NavigateUrl = String.Format("{0}/{1}", tmpURL, n.id), Text = n.Text, id = n.id, SubItems = new List<SubNav>( from si in ds.NavigationBottomLevels where si.parentID == n.id select new SubNav { id = si.id, level = si.NavLevel, NavigateUrl = String.Format("{0}/{1}/{2}", tmpURL, n.id, si.id), parentID = si.parentID, Text = si.Text } ) }; List<TopNav> TopNavigation = TopNavs.ToList();

It might not be the "coolest" but for a lot of people who want to have dynamic navigation, its sweet not to have to muddle around in the usual looping logic that comes with that. LINQ is, if anything a time saver in this case.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-29 16:54

By far the most impressive Linq implementation i've ever come across is the Brahma framework.

It can be used to offload parallel calculations to the GPU using 'Linq to GPU'. You write a 'query' in linq, and then Brahma translates it into HLSL (High Level Shader Language) so DirectX can process it on the GPU.

This site will only let me paste one link so try this webcast from dotnetrocks:

http://www.dotnetrocks.com/default.aspx?showNum=466

Else google for Brahma Project, you'll get the right pages.

Extremely cool stuff.

GJ

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-29 16:54

Actually, I'm quite proud of this for generating Excel docments: http://www.aaron-powell.com/linq-to-xml-to-excel

查看更多
登录 后发表回答